JS DOM: Get Element by ID, Name, Class etc
Here's how to get element in a HTML.
Get Current Script Element
Get Element by Matching the Value of the “id” Attribute
document.getElementById(idString)
-
Return a non-live element, or
null
if not found.document.getElementById("wjghr").style.color = "red";
Get Elements by Tag Name
document.getElementsByTagName(tagName)
-
Return a Live Object of HTMLCollection.
Array.from(document.getElementsByTagName("p"), (x) => { x.style.color = "red"; });
Get Elements by Matching the Value of the “class” Attribute
document.getElementsByClassName(classValues)
-
Return a Live Object of HTMLCollection.
Array.from(document.getElementsByClassName("js"), (x) => { 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: List Add Remove Class
Get Elements by Matching the Value of the “name” Attribute
document.getElementsByName(val)
-
Return a Live Object of NodeList, of all elements that have attribute
name=val
.Array.from(document.getElementsByName("xyz") , (x) => { 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 .
document.querySelectorAll(cssSelector)
-
- Get elements that match the CSS Selector Syntax
- Return a non-live NodeList.
Array.from(document.querySelectorAll("p"), (x) => { x.style.color = "red"; });
Iterate Over HTMLCollection or NodeList
Basic DOM Element Methods
- JS DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Element Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: List, Add, Remove Class Attribute
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler