lördag 19 februari 2011

I don't understand why

1)
The following code does not give the expected result. I think it should alert "P", and not "H1" as it does. What do you think?

<html>
  <head>
    <title>This is a Document!</title>   
  </head>
  <body>
    <h1>This is a header!</h1>
    <p id="excitingText">
      This is a paragraph! <em>Excitement</em>!
    </p>
    <p>
      This is also a paragraph, but it's not nearly as exciting as the last one.
    </p>
   
<script>

var theHtmlNode = document.childNodes[0]; // the first child of document is HTML

var theBodyNode = theHtmlNode.childNodes[1]; // the second child of HTML is BODY

var theParagraphNode = theBodyNode.childNodes[1]; // the second child of BODY is P

alert( "theParagraphNode is a " + theParagraphNode.nodeName + " node!" ); // so how can this alert H1?

</script>
  </body>

</html>

2)
Also this is very confusing: 

<html>
  <head>
    <title>This is a Document!</title>  
  </head>
  <body>
    <h1>This is a header!</h1>
    <p id="excitingText">
      This is a paragraph! <em>Excitement</em>!
    </p>
    <p>
      This is also a paragraph, but it's not nearly as exciting as the last one.
    </p>
   
<script>
var theParagraphNode = document.getElementById('excitingText');
if ( document.firstChild.lastChild.childNodes[3] == theParagraphNode ) {
 alert( "theParagraphNode is exactly what we expect!" );
}
</script>
  </body>

</html>


Why is "P" now the fourth node?
Does it count like this:
1 HTML
2 BODY
3 H1
4 P

or how does it work? 


glenn.hellquist@gmail.com
webbkraft.com

/*#p2pu-Jan2011-javascript101*/

2 kommentarer:

  1. I think you have to get childNodes[3] when going after the paragraph node. This is because there is a whitespace text node after the body node, and there is another whitespace text node after the header node.

    SvaraRadera
  2. You were right there. I changed the html code so that everything but the script were on one singel line,and suddenly I hade to change the number from 3 to 1 to get the alertbox.

    Very interesting, and that explains why I got "#text" as result then changing the number before. Thanx alot Barry!

    With your help I also got the first problem solved - I changed to:
    theBodyNode.childNodes[3];
    wich gave the result "P"
    I wonder why they don't mention this in the text, it's obviously worth knowing.

    SvaraRadera