Modifying Attributes and Classes By Chloe

In this example, in the HTML page we have an 'img' element with no 'src' attribute and an id of 'imageEx'.
Using JavaScript we added the cat image you can see. We retrieved the img element via the id. We then used the .setAttribute with two arguments - the first one was the attribute added, the second one the image pathway.

        let setEx = document.getElementById('imageEx');

        setEx.setAttribute('src', '../images/cartoon-cat-free.png');

        
Using className method I have the red class
I have the blue class, written in the HTML page.
In the above example, we have two div that were both originally styled using the class name 'blue'. In Javascript using the .className method we applied the 'red' class to the first div, which over-rode any existing classes it had. Because it also have bootstrap styling it also over-rode all of that, which is why it is no longer the full length of the viewport. Below is the css and JS code:

            .red {
        text-align: center;
        font-size: 13px;
        font-family: 'Roboto Mono', monospace;
        border: 3px dashed red;
        margin-bottom: 25px;
        margin-left: 15px;
        }

.blue {
    text-align: center;
    font-size: 13px;
    font-family: 'Roboto Mono', monospace;
    border: 3px dashed blue;
    margin-bottom: 25px;
    margin-left: 15px;
}

let blueEx = document.getElementById('blue');

blueEx.className="red";

                
I have a blue background because of the clasList.add(); method.
My class was added via the HTML page.
Using the classList.add(); method does not over-ride the existing classes like className does, instead it adds extra classes to the existing classes. Below is the CSS and JS code for the above divs.


                .background {
            background-color: aqua;
                    }

                    let backgroundEx = document.getElementById('red');

                    backgroundEx.classList.add('background');
                
Click here to return back to The DOM cheatsheet!