Jump to content

JAVASCRIPT nodeList/nodeCollection


Recommended Posts


I have a problem when it comes to traversing through DOM nodes and accessing their data(values).

Please have a look at the following code


<!DOCTYPE html>
<title>Page Title</title>
<script src="js.js"></script>
	<div id="div1" class="div1">
		<img src="1.png" style="width:100px;height:100px;"/>
		<h1>This is a Heading1</h1>
		<p>This is a paragraph1.</p>
		<button onclick="a(0);">Press me</button>
	<div id="div1" class="div1">
		<img src="2.jpeg" style="width:100px;height:100px;"/>
		<h1>This is a Heading2</h1>
		<p>This is a paragraph2.</p>
		<button onclick="a(1);">Press me</button>
	<div id="div1" class="div1">
		<img src="3.jpeg" style="width:100px;height:100px;"/>
		<h1>This is a Heading3</h1>
		<p>This is a paragraph3.</p>
		<button onclick="a(2);">Press me</button>


var elements = document.getElementsByClassName("div1");

function a(index)
	var d = elements[index].childNodes[3].nodeValue;

Okay so according to my understanding if I want to access and alert the first div's h1 text value which is "This is Heading1" then my JavaScript code should be

var d = elements[index].childNodes[1].nodeValue;

However I do not get the text value?

Also nodeValue gives me NULL if I use innerHTML I get the text value but at childNodes[3] and not childNodes[1] where you'd expect it to be?

Also this example contradicts everything you find at https://www.w3schools.com/js/js_htmldom_navigation.asp

Can someone please elaborate on this as it is very important to understand and I am tearing my hair out trying to figure this out.


Edited by Iven
Link to comment
Share on other sites

Thank you so much dsonesuk for bringing clarity and using such an simple example.

That makes so much more sense.

So I am correct in assuming that node doesn't always just mean elements? It can be spaces too?


Link to comment
Share on other sites

Yes! spaces are Text nodes, if you want to be element specific only, use '.children' instead

            function a(index)
                var d = elements[index];
                alert("Children length: " + d.children.length);
                alert("childNodes length " + d.childNodes.length);


Edited by dsonesuk
Link to comment
Share on other sites

Both work exactly the same if used correctly, with nodeValue you have to access the parent element text node first using childNode[0] then nodeValue (childNode[0].nodeValue), with .innerHTML its simple needs a reference to parent element in question to add or retrieve text within it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...