JS DOM: Get Element by ID, Name, Class etc

By Xah Lee. Date: . Last updated: .

Here's how to get element in a HTML.

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: JS DOM: Class Attribute (get add remove toggle)

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)
Array.from(
 document.querySelectorAll("p"),
 (x) => {
  x.style.color = "red";
 },
);

Get current script element