JS DOM: Get Element by ID, Name, Class etc
Here's how to get element in a HTML.
Get element by id
document.getElementById(idString)-
Get element by matching the value of the
idattribute.Return a non-live element, or null if not found.
const x = document.getElementById("HCBX9"); if (!x) throw new Error("#HCBX9 missing"); x.style.color = "red";
Get elements by tag name
document.getElementsByTagName(tagName)-
Return a Live Object of HTMLCollection.
for (const x of document.getElementsByTagName("p")) { x.style.color = "red"; }
Get elements by class
document.getElementsByClassName(classValues)-
Get elements by matching the value of the
classattribute.Return a Live Object of HTMLCollection.
for (const x of document.getElementsByClassName("vBw3Q")) { x.style.color = "red"; } Note: The classValues can be multiple classes separated by space. e.g.
"aa bb", and it'll get elements that has both class “aa” and “bb”.<p class="aa">1</p> <p class="bb">2</p> <p class="bb aa">3</p> <p class="bb cc aa">4</p> <script>document.getElementsByClassName("aa bb");</script> <!-- return elements 3 and 4. --> See also: JS DOM: Class Attribute methods
Get elements by “name” attribute
document.getElementsByName(val)-
Get elements by matching the value of the
nameattribute.Return a Live Object of NodeList, of all elements that have attribute
name=val.for (const x of document.getElementsByName("xyz")) { x.style.color = "red"; }
Get elements by css selector syntax
document.querySelector(cssSelector)-
Return a non-live first element that match the CSS Selector Syntax.
if no match, return null.
document.querySelectorAll(cssSelector)-
- Get elements that match the CSS Selector Syntax
- Return a non-live NodeList. (empty if no match.)
for (const x of document.querySelectorAll("p")) { x.style.color = "red"; }