Javascript DOM HTML Node firstChild Property Navigating HTML Document

Description

Javascript DOM HTML Node firstChild Property Navigating HTML Document

View in separate window

<!DOCTYPE html> 

<html lang="en"> 
<body> 
    <h1 id="heading1">My Heading</h1> 
    <p id="paragraph1">This is some text in a paragraph</p> 
    <script> 
        let htmlElement; // htmlElement stores reference to <html> 
        let headElement; // headingElement stores reference to <head> 
        let bodyElement; // bodyElement stores reference to <body> 
        let h1Element; // h1Element stores reference to <h1> 
        let pElement; // pElement stores reference to <p> 

        htmlElement = document.documentElement; 
        headElement = htmlElement.firstChild; 

        document.getElementById("demo").innerHTML = headElement.tagName; 

        if (headElement.nextSibling.nodeType == 3) { 
            bodyElement = headElement.nextSibling.nextSibling; 
        } else { /*from www  .j a va2 s.  c  o  m*/
            bodyElement = headElement.nextSibling; 
        } 

        document.getElementById("demo").innerHTML += " "+bodyElement.tagName; 

        if (bodyElement.firstChild.nodeType == 3) { 
            h1Element = bodyElement.firstChild.nextSibling; 
        } else { 
            h1Element = bodyElement.firstChild; 
        } 

        document.getElementById("demo").innerHTML += " "+ h1Element.tagName; 
        h1Element.style.fontFamily = "Arial"; 

        if (h1Element.nextSibling.nodeType == 3) { 
            pElement = h1Element.nextSibling.nextSibling; 
        } else { 
            pElement = h1Element.nextSibling; 
        } 

        document.getElementById("demo").innerHTML += " "+ pElement.tagName; 
        pElement.style.fontFamily = "Arial"; 

        if (pElement.previousSibling.nodeType == 3) { 
            h1Element = pElement.previousSibling.previousSibling; 
        } else { 
            h1Element = pElement.previousSibling; 
        } 

        h1Element.style.fontFamily = "Courier"; 
    </script> 
    <p id="demo"></p>
</body> 
</html> 



PreviousNext

Related