JS: Get Element by ID, Name, Class etc

By Xah Lee. Date: . Last updated: .

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 Object of element. Return null if not found.

document.getElementById("xyz").style.color="green";

Get Elements by Tag Name

document.getElementsByTagName(tagName)

Return a Live Object of HTMLCollection.

for (let e of document.getElementsByTagName("p")) { e.style.color = "green"; }

Get Elements by Matching the Value of the “class” Attribute

document.getElementsByClassName(classValues)

Return a Live Object of HTMLCollection.

for (let e of document.getElementsByClassName("js")) { e.style.color = "green"; }

Note: The classValues can be multiple classes separated by space. For example: "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 Attribute

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.

// make all elements with name="xyz" green.
for (let e of document.getElementsByName("xyz")) { e.style.color="green"; }

Get Elements by CSS Selector Syntax

document.querySelector(cssSelector)

Return a non-live Object of first element that match the CSS Selector Syntax

document.querySelectorAll(cssSelector)

Return a non-live Object of NodeList, of elements that match the CSS selector.

for (let e of document.querySelectorAll ("p")) { e.style.color="green"; }

How to Loop Thru Result

BUY ΣJS JavaScript in Depth

Basic DOM Element Methods