JS & Dom - Tips & Tricks #1
Fri Jan 06, 2017 · 320 words

There are many ways to read content from elements and nodes. Here’s another one that allows you to read and write an individual node’s value. It uses the nodeValue property of the Node interface. The nodeValue of an element will always return null, whereas text nodes, CDATA sections, comment nodes, and even attribute nodes will return the text value of the node. To demonstrate its use, I’ll use the following HTML:

<body class="home">
  <p>Example. <span>Example paragraph one.</span></p>
  <p>Example paragraph two.</p>
  <p>Example paragraph three.</p>
  <p>Example paragraph four.</p>
  <!-- comment text -->
</body>

Now I’ll run the following JavaScript to read/write a few of the nodes:

let b = document.body,
    p1 = document.querySelector('p');

// reading node values
console.log(b.nodeValue); // null for all elements
console.log(b.attributes[0].nodeValue); // "home"
console.log(b.childNodes[7].nodeValue); // " comment text "

// changing nodeValue of first node inside first paragraph p1.firstChild.nodeValue = 'inserted text<br>';

Notice the second console.log is displaying the text of an attribute node. This would be the equivalent of using getAttribute(), with the difference being that getAttribute() acts on elements, whereas nodeValue can be applied to any type of node.

Also notice that I’m using nodeValue to read the contents of an HTML comment. This is one of many ways you can do this. This would be the equivalent of reading the textContent property or data property of the comment node. As you can see from the final line in that code example, I’m able to define the nodeValue of one of the text nodes, so this isn’t read-only.

A few other things to note regarding defining the nodeValue property: Setting nodeValue will return the value that was set, and you cannot set the nodeValue when the nodeValue is null (unless of course you change it to null, which is the same as an empty string that’s changeable later).

MDN’s article on nodeValue has a chart that lists the different node types and what their nodeValue will return.


back · he thought · he could · so he did · main