Click here to Skip to main content
15,748,749 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
OK, guys, this one is driving me nuts. I'm doing a little bit of Javascript studying and trying to understand how the JS is resolving this. Here's the code fragment:

<!DOCTYPE html> 
		<title>JavaScript Programmer's Reference</title>
		<p id="myParagraph">This is my paragraph! <span class="hideme1">Lorem ipsum</span> dolor sit amet.
		<p class="hideme2">Another paragraph!</p>
			alert(document.childNodes[1].childNodes[2].childNodes[3].className);  // will alert "hideme2"

Now, if the HTML (DOM?) is organized in a tree then how does the reference "document.childNodes[1].childNodes[2].childNodes[3] get us to that 2nd paragraph in the body? The alert displays 'hideme2'.

I can see that DOCTYPE is document.childNodes[0] and the HTML block is document.childNodes[1]. I would expect , then to be document.childNodes[1].childNodes[1], right? I don't see how there is even a document.childNodes[1].childNodes[2], let alone a 3rd level under it.

I'm obviously missing something here but only see 3 elements that are subordinate to the body, 2 paragraphs and the block. I would expect the 2nd paragraph to, then, be document.childNodes[1].childNodes[1].childNodes[1] (Assuming everything is 0-based, as usual). What am I not seeing here?



<b>What I have tried:</b>

Scratching my head and studying DOM references.
Updated 3-Oct-18 5:59am

1 solution

Try using the browser's developer tools. Firefox has a DOM explorer which might help. Alternatively, this online DOM viewer[^] works pretty well.
    [0] = <!DOCTYPE html>
    [1] = <html>
            [0] = <head>
            [1] = #whitespace#
            [2] = <body>
                    [0] = #whitespace#
                    [1] = <p id="myParagraph">
                    [2] = #whitespace#
                    [3] = <p class="hideme2">[^]
Share this answer
Maciej Los 3-Oct-18 14:45pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900