Skip to content

Instantly share code, notes, and snippets.

@nikibrown
Created March 22, 2018 16:07
Show Gist options
  • Save nikibrown/d8c1c4fc562c26439b5921201999624f to your computer and use it in GitHub Desktop.
Save nikibrown/d8c1c4fc562c26439b5921201999624f to your computer and use it in GitHub Desktop.
Node Value Stuff

childNodes, firstChild, and nodeValue - oh my!

first, let's look at childNodes. this property gives you a list of nodes that are direct children of the node the property is called on. here's an example. consider the following html and javascript:

<section>
    <div>
        <h1>hi there!</h1>
    </div>
</section>
var section = document.getElementsByTagName('section')[0];
var childNodes = section.childNodes;
console.log(childNodes);

that will print out the direct child nodes of the section element, meaning that it will print out the info for the div, but not the h1 because the h1 is not its direct child.

firstChild is similar to childNodes, but it only returns the very first child.

let's use this HTML again:

<section>
    <div>
        <h1>hi there!</h1>
    </div>
</section>

if i use the following javascript:

var section = document.getElementsByTagName('section')[0];
var first = section.firstChild;
console.log(first);

it will give me a #text node, which seems weird, right? we would expect the firstChild of the section node to be the div. but in order to preserve the white space between those elements, a text node is inserted. so the property is actually behavior properly!

next, let's talk about nodeValue. it's important to know that there are many different types of nodes -- Document, Element, and Comment are all examples -- but nodeValue only gives you a useful non-null value for certain types of nodes. if you take a look at the table on this page, you can see that of all the nodes we typically use day-to-day, only Text and Comment return a value.

so, let's expand on the first example.

<section>
    <div>
        <h1>hi there!</h1>
    </div>
</section>
var section = document.getElementsByTagName('section')[0]; //capturing the section ...
var div = section.childNodes[1]; //drilling down to capture the div
var h1 = div.childNodes[1]; //drilling down further to capture the h1
var textNode = h1.childNodes[0]; //grabbing the textNode inside of the h1
console.log(textNode.nodeValue); //"hi there!"

all of these properties can seem very intricate, and it's okay if you don't have them memorized right now. but it's important to know that there are many ways to slice and dice the DOM, and that there is a tool for just about any objective you might have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment