Day 36 - Querying Webpages pt.2
by Nino · 22 things on Twos
- Getting Tags and Classes 1/1: Tag and Class
- `document.getElementsByTagName("li")` get a collection of elements of the same tag type
- `el[0].innerHTML` display the first element of a group (like “li”)
- `el.length` access the length property of the collection
- `document.getElementsByClassName(”urgent”)` return a collection containing specific elements of a class
- `document.getElementsByClassName("urgent important")` if a class has more than one name
- ---
- Querying Multiple Elements
- `document.querySelectorAll()` get array-like lists of elements
- `document.querySelectorAll(".urgent")` works for both tag and class names
- `document.querySelectorAll("h3.news")` look for specific elements, like a `h3` element of class `news`
- `document.querySelectorAll(".movie, .tech")` access elements of **either** two different classes at the same time, add comma
- `document.querySelectorAll(".sports.news")` retrieve elements that have both the class `sports` and `news`
- `document.querySelectorAll(".movie, .sports, img")` retrieve either classes and with an image element
- ---
- Toggling CSS Classes
- `el.setAttribute("class", "italic")`
- `classList.add()` add a class
- `classList.remove()` remove a class
- `classList.toggle()` automatically add or remove a class
- `classList.remove("highlight", "underline")` remove multiple classes
- `setAttribute()` overwrites the element’s classes while `classList` does not