0

I am new to javascript programming so feel free to correct me . In the code below why do i have to write nextSibling twice instead of just once , cause i checked the definition and it said :returns the next child node of an element at the same level as the current child node.

And then again referencing h1 i have to write firstChild & again nextSibling(Why is nextSibling present in this line)I am confused here , please explain or if possible give me a good link to a website that explains my confusion below. Thank You

 <!DOCTYPE html>
<html lang="en">
<head>
    <title>Chapter 8, Example 4</title>
</head>
    <body>
      <h1 id="heading1">SOME HEADING</h1>
      <p id="para1">Welcome to my Humble website.</p>

      <script>
      var html_element = document.documentElement;
      alert(html_element.tagName); //HTML

      var head_element = html_element.firstChild;
      alert(head_element.tagName); //HEAD

      var body_element = head_element.nextSibling.nextSibling;
      alert(body_element.tagName); // BODY

      var h1_element = body_element.firstChild.nextSibling;
      alert(h1_element.tagName); //H1

      var p_element = h1_element.nextSibling.nextSibling;
      alert(p_element.tagName); //P


      </script>


    </body>
</html>
ritam bala
  • 139
  • 1
  • 7
  • Can't you use jQuery ? It's really useful for simplifying dom queries. – ADreNaLiNe-DJ Feb 16 '16 at 11:58
  • 1
    use `nextElementSibling` to skip the "empty" text nodes (that exist between tags) ... also use `firstElementChild` for the same reasons – Jaromanda X Feb 16 '16 at 11:58
  • 1
    p.s. `body = document.body` ... `head = document.head` (note: document.head does not exist in IE8 or earlier) – Jaromanda X Feb 16 '16 at 12:00
  • `document.body` isn't this one better? Although _jX_ already answered at first comment. – Jai Feb 16 '16 at 12:03
  • as a brief explanation ... between `` and `

    ` you have a line break, and some spaces ... therefore the first child node of `` is a text node ... however, the first ELEMENT child is `

    `

    – Jaromanda X Feb 16 '16 at 12:03

0 Answers0