Describes the sample code of the Javascript encapsulation id, class, and element selector in detail.

Source: Internet
Author: User
This article mainly introduces how to encapsulate id, class, and element selector in Javascript. It provides detailed sample code, which has some reference value for your understanding and learning, let's take a look. This article mainly introduces how to encapsulate id, class, and element selector in Javascript. It provides detailed sample code, which has some reference value for your understanding and learning, let's take a look.

Each browser supports the following three methods:

1,document.getElementById()

2,document.getElementsByName()

3,document.getElementsByTagName()

Therefore, the browser compatibility should be considered when encapsulating the selector.

The sample code is as follows:

Script // encapsulate id selector function $ (selector) {var c = selector. substring (0, 1); // obtain the first character if (c = "#") {return document. getElementById (selector. substring (1, selector. length); // return the corresponding element} // encapsulate the class selector function $ (selector) {var className = selector. substring (1); // retrieve the element whose index is 1. // determine whether the browser supports getElementsByClassName if (document. getElementsByClassName) {return document. getElementsByClassName (className) // document. querySelectorAll ('. cls ') compatibility problem} else {// document. getElementsByTagName ('*') + Regular Expression // \ s blank character ^ start $ end var reg = new RegExp ('^ | \ s' + className +' $ | \ s '); var elems = document. getElementsByTagName ("*"); // obtain all the elements on the page. var arr = []; // Save the obtained elements of the specified className for (var I = 0; I
 
  

Summary

The above section details how to share the sample code of Javascript encapsulation id, class and element selector. For more information, see other related articles in the first PHP community!

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.