Categories
Code

Modifying DOM Elements

Once we can grab DOM elements, we can modify them. There are several methods to change DOM elements. If we would like to set the attribute on an element…

let myElem = document.getElementById(‘elementId’); myElem.setAttribute(‘attributeName’,‘attributeValue’
); 

If we would like to add a class to an element…

let myElem = document.getElementById(‘elementId’); myElem.classList.add(‘className’); 

If we would like to change the style of an element…

let myElem = document.getElementById(‘elementId’); myElem.style.color = ‘#333’; 

Here we can use color names, RGB(a), hex codes and HSL(a).

We can even change the text content of an element…

let myElem = document.getElementById(‘elementId’); myElem.textContent = ‘Here is some new text!’; 

Happy Coding!

Clay Hess