JavaScript: 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(id_string)
Return a non-live Object of element. Returns null if not found.
document.getElementById("xyz").style.color="green";

Get Elements by Tag Name

document.getElementsByTagName(tag_name)
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(class_values)
Return a Live Object of HTMLCollection.
for (let e of document.getElementsByClassName("js")) { e.style.color = "green"; }

Note: The class_values 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>
<!-- it'll get 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(css_selector)
Return a non-live Object of first element that match the CSS Selector Syntax .
document.querySelectorAll(css_selector)
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

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc