Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

InnerHTML

In this tutorial, we use the innerHTML property to retrieve the content of an HTML element. However, learning the other methods mentioned above is valuable for understanding the tree structure and how to navigate the DOM.

DOM Root Nodes

There are two special properties that provide access to the entire document:

  • document.body – Represents the body of the document.
  • document.documentElement – Represents the entire document (usually the <html> element).

Example

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>

<p id=”demo”></p>

<script>
document.getElementById(“demo”).innerHTML = document.body.innerHTML;
</script>

</body>
</html>

Example

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.documentElement</p>

<p id=”demo”></p>

<script>
document.getElementById(“demo”).innerHTML = document.documentElement.innerHTML;
</script>

</body>
</html>

The nodeName Property

The nodeName property specifies the name of a node:

nodeName is read-only.

  • For an element node, nodeName is the same as the tag name.
  • For an attribute node, nodeName is the attribute name.
  • For a text node, nodeName is always #text.
  • For a document node, nodeName is always #document.

Example

<h1 id=”id01″>My First Page</h1>
<p id=”id02″></p>

<script>
document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).nodeName;
</script>

Note: The nodeName property always contains the tag name of an HTML element in uppercase.

The nodeValue Property

The nodeValue property specifies the value of a node:

  • For element nodes, nodeValue is null.
  • For text nodes, nodeValue contains the text itself.
  • For attribute nodes, nodeValue contains the attribute value.

The nodeType Property

The nodeType property is read-only and returns the type of a node.

Example

<h1 id=”id01″>My First Page</h1>
<p id=”id02″></p>

<script>
document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).nodeType;
</script>

The key nodeType properties are:

Node

Type

Example

ELEMENT_NODE

1

<h1 class=”heading”>W3Schools</h1>

ATTRIBUTE_NODE

2

 class = “heading” (deprecated)

TEXT_NODE

3

W3Schools

COMMENT_NODE

8

<!– This is a comment –>

DOCUMENT_NODE

9

The HTML document itself (the parent of <html>)

DOCUMENT_TYPE_NODE

10

<!Doctype html>