Get Element ById
If an element has the id attribute, we can get the element,
no matter where it is.
let el = document.getElementById("mydiv");
console.log(el.innerHTML);
el.style.color = "red";
Global variable
Also, there’s a
global variable named by id that references the element.
But it is supported
mainly for compatibility. Not recommended.
mydiv.style.color = "red";
Query selector
querySelectorAll
By far, the
most versatile method.
This returns the
first element for the given CSS selector.
let el = document.querySelector('div.myClass');
console.log(el.innerHTML);
This returns element matching the given
CSS selector.
let elements = document.querySelectorAll('ul > li:last-child');
for (let elem of elements) {
console.log(elem.innerHTML);
}
getElementsByClassName
Today, they are
mostly history, as querySelector is more powerful and shorter to write.
let el1 = elem.getElementsByTagName(tag);
let el2 = elem.getElementsByClassName(className);
Task
Add
.myClass to each li Header.
Hint: use
querySelector
task
for (let el of elements) {
el.classList.add("myClass");
}