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!