Traversing the DOM By Chloe

In this example, I have made a simple unordered list, with four list elements as child nodes.
In the JS script page, I have used the firstElementChild and lastElementChild method to give them a background color of yellow and pink. Below is the JS code for this:
        let childEx1 = document.getElementsByTagName("ul")[0];

        childEx1.firstElementChild.style.background = "yellow";

        childEx1.lastElementChild.style.background = "pink";
        
I have used a for...of loop to iterate through all the children of the unordered list. As you will see I have used the [1] at the end which defines which unordered list it will target. If I used [0] it will have changed the border of the above example. Below is the JS code for this:

        let childEx2 = document.getElementsByTagName("ul")[1];

        for(let element of childEx2.children){

        element.style.border = '2px dashed purple';
        }
        
In this example, I have targeted the elements using the sibling methods. We have first targeted the ul list and stored it in a variable called 'sibling', we have then targeted the second child [1] of the 'sibling' variable and stored it under the siblingEx variable.
From there we have used the sibling methods to change the styles.

        let sibling = document.getElementsByTagName("ul")[2];

        let siblingEx = sibling.children[1];

        siblingEx.previousElementSibling.style.background = "green";

        siblingEx.nextElementSibling.style.border = "3px dashed orange";
        
Click here to return back to The DOM cheatsheet!