DOM: Get Elements by ID, Tag, Name, Class, CSS Selector

By Xah Lee. Date: . Last updated: .

Here's how to get element in a HTML.

Get Current Script Element

document.currentScript
Return the current script element. [see DOM: Get Current Script Element]

Get Element by Matching the Value of the “id” Attribute

document.getElementById(id_string)
Return a non-live element object. Returns null if not found.
document.getElementById("xyz").style.color="green";

Get Elements by Tag Name

document.getElementsByTagName(tag_name)
Return a live 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 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 3 and 4. -->

See also: DOM: List/Add/Remove Class Attribute

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

document.getElementsByName(val)
Return a live NodeList, of all elements that have name=val.

Here's a sample HTML:

<p name="abc">1</p>
<div class="zz" name="xyz">2</div>
<div class="zz" name="xyz">3</div>

<form>
<input name="xyz" type="text" size="20">
</form>

Here's JavaScript code that makes 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 first element that match the CSS Selector Syntax .
document.querySelectorAll(css_selector)
Return a non-live NodeList, of elements that match the CSS selector.
for (let e of document.querySelectorAll ("p")) { e.style.color="green"; }

How to Loop Thru Result

Since JS2015, both HTMLCollection and NodeList are Iterable objects.

Use for-of Loop.

for (let v of eleResult) {code}

For before JS2015 code, do like this:

Array.prototype.forEach.call(eleResult, f)

see:

What's Live Object

DOM: What Does Live Object Mean?

HTMLCollection vs NodeList

DOM: NodeList vs HTMLCollection

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js