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

来源:互联网 发布:mac更换系统字体 编辑:程序博客网 时间:2024/04/28 22:34

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

 

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 elementsconsole.log(myList.length); // show number of itemsmyList[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” attributevar 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("‹name value›") to get all elements that have thename="‹name value›" 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” attributevar xyz = document.getElementsByName("xyz");xyz[0].style.color="red"; // make the first one red

Try it here: JavaScript test page: getElementsByName Example.

Get Elements using CSS Selector Syntax

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

var myList = document.querySelectorAll("span.x, span.y");

This will select all “span” tags that have class value of “x” or “y”.

The syntax for the argument is the same as CSS selector. 〔☛ CSS Selector Syntax〕

If the argument refers to pseudo-selectors (⁖ a:hover), it returns empty.

“querySelectorAll” returns a non-live NodeList of element objects.

test page JavaScript test page: querySelectorAll

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.

  • JavaScript: Frequently Used DOM Methods
  • JavaScript: Get a Element's Attribute/Properties
原创粉丝点击