By ID, TagName, ClassName, Name, CSS selector get element

Source: Internet
Author: User
Tags tagname

Original acknowledgement: < http://xahlee.info/js/js_get_elements.html >

    1. through ID Get element :

document.getElementById (ID string) return element Object, If it fails, get NULL

Note ID should be unique within the page, but in iframe is seen as another HTML page

    1. through TagName Get element

document.getelementsbytagname (tagname) return Element Object Collection . tagname such as DIV, span , P ,

    var myList = document.getElementsByTagName ("P"); // Get all P Elements

Mylist.length; // returns the total number of p elements
Mylist[0].style.color = "Red"; // modifies the first element's style

    1. through ClassName Get element

document.getelementsbyclassname ("class values") returns the element object collection .

var myList = Document.getelementsbyclassname ("abc");
Mylist[0].style.color = "Red"; Make the first one red

the class values can be multiple, separated by a space . like "AA BB" ,

an element can also have multipleClassName,For example:
<Pclass="AA">1</P>

<Pclass="BB">2</P>

<Pclass="BB aa">3</P>

<Pclass="BB cc AA">4</P>

<Script>document.getelementsbyclassname ("AA BB"); </Script>

Will bewill get the third and fourth elements

    1. through Name Get element

document.getelementsbyname ("Name value") returns the element object collection .

Like what:
<pname= "ABC" >you</p>
<divclass= "zz" name= "XYZ" >me</div>
<divclass= "zz" name= "XYZ" >her</div>

<form>
<inputname= "xyz" type= "text" size= ">"
</form>

var xyz = document.getelementsbyname ("xyz");
Xyz[0].style.color= "Red"; Make the first one red

    1. through CSS Selector Get element

     document.queryselectorall (CSS selector) returns element Object Collection , css selector is string, can be multiple separated by commas .

var xx = Document.queryselectorall ("Span.a, span.c");

for (var i = 0; i < xx.length; i++) {
Xx[i].style.color= "Red";
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.