MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

JavaScript: Get Elements by ID, Tag, Name, Class

Xah Lee, , …,

This page shows you ways to get a element in JavaScript.

Get Element by ID

Use getElementById(‹id string›). Example:

var myObj = document.getElementById("xyz");

myObj.style.color="red"; // change color to red

Note: ID must be unique in each HTML page.

Get Elements by Tag Name

Use document.getElementsByTagName("‹tag name›") to get all ‹tag name› elements.

Example, getting all “p” elements and make the first one red.

var myList = document.getElementsByTagName("p"); // get all p elements

console.log(myList.length); // show number of items

myList[0].style.color="red"; // make the first one red

Get Elements by Class Name

You can use document.getElementsByClassName("‹class value›") to get all elements by class.

Here's JavaScript code.

// get element by value of the “class” attribute
var myList = document.getElementsByClassName("abc");

myList[0].style.color = "red"; // make the first one red

Here's a test page: JavaScript test page: getElementsByClassName Example.

Note: A HTML tag can have multiple classes. In HTML file, the correct syntax is to use ONE “class” attribute, and separate the value string by space. See: More Than One Class for HTML Tag.

Get Elements by Matching the Value of the Name Attribute

Use document.getElementsByName("abc") to get all elements that have the name="abc" attribute and value pair.

Here's a sample HTML:

<p name="abc">you</p>
<div class="zz" name="xyz">me</div>
<div class="zz" name="xyz">her</div>

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

Here's JavaScript code that makes the first element with name="xyz" red.

// get element by value of the “name” attribute
var xyz = document.getElementsByName("xyz");
alert(xyz.length); // show number of items
xyz[0].style.color="red"; // make the first one red

Try it here: JavaScript test page: getElementsByName Example.

Get Elements by Tag & Class

You can use “querySelectorAll” to get all HTML elements of a given tag name and class value. Example:

var myList = document.querySelectorAll("p.xyz");

This will select all “p” tags that have class value of “xyz”. The syntax for the argument is the same as CSS selector. 〔☛ CSS 2.1 & CSS 3 Selector Syntax

Return Value of getElements Methods

The methods {getElementById, getElementsByTagName, getElementsByClassName, …} return a collection, not array. You cannot use array methods on them. Use “for loop” instead.

For detail, see: JavaScript: Array vs NodeList vs HTMLCollection.

blog comments powered by Disqus