Accessing elements using the DOM By Chloe


Although all of this can be done in the CSS style sheet, it is useful to use JS because then you can make the website interactive for the user, e.g. when clicked the background changes colour. But for now we will just access the elements and change the styles.

I was accessed using the ID method!
Related code:
HTML:
A div with the id='example'
JAVASCRIPT:
let idExample = document.getElementById('example');

                idExample.style.background = "yellow";
                idExample.style.border = "3px dashed blue";
            
I have a class of JSEXAMPLE
I have a class of JSEXAMPLE
I have a class of JSEXAMPLE1
I have a class of JSEXAMPLE1
When using the classNames method, JS will select all the classes with the same name and put it into an array. You can either use an array index to target just one of the class names, or more often you would use a for loop to loop through the length of an array and apply it to all the classes with the same name.
RELATED JS CODE:
                let classExample = document.getElementsByClassName('JSEXAMPLE');
                let classExample2 = document.getElementsByClassName('JSEXAMPLE1');

                classExample[0].style.border = "3px solid purple";
                classExample[1].style.background = "pink";

                for (i = 0; i < classExample2.length; i++) {
                    classExample2[i].style.border="2px dashed black";

                
I am a section!!
I am also a section!
The third and last section!
A less common way to access elements is with tag method.
In our example we have made three sections and have targeted them all using a for loop.
JS CODE:
            let tagExample = document.getElementsByTagName('section');

            for (i=0; i< tagExample.length; i++){
            tagExample[i].style.background="#cffffa";
            tagExample[i].style.border = "2px solid purple";
                }
            
I was accessed used a query selector! I have an id of queryEx.
In JS you can access single elements using the query selector method. If there are more elements with the same class/tag query selector would select the first one.
        let queryExample = document.querySelector('#queryEx');

        queryExample.style.background = "orange";
        
Hello
My
Name
Is
Chloe!
The query selector all method will select all classes/elements with the same name and style them accordingly. Our above example is 5 divs all with the class of 'Query-Selector-All'.

            let queryAllExample = document.querySelectorAll('.Query-Selector-All');
            queryAllExample.forEach(query =>{
            query.style.border = "2px dashed green";
                })
            
PLEASE NOTE THAT ALL VARIABLES SHOULD BE DEFINED AT THE TOP OF THE JAVASCRIPT STYLE SHEET WITH THE CODE BELOW!
Click here to return back to The DOM cheatsheet!