When new users use native JavaScript, they often use document.getElementById, document.getelementbyclassname and document.getElementsByTagName to get elements and then operate them. However, the document.getElementsByClassName method is not supported in the version below IE9, so many students who are new to js are often confused about this problem. Here we encapsulate the functions of the three methods, so that they can perfectly use the three methods, hoping to help you.
The $symbol used here is the function name. At the same time, when passing parameters, the second parameter can not be written.
- //You can find elements by id, class, element
- //param (string): ාid.class tag
- //obj: parent element
- //First, determine which way to get the elements
- function $(param, obj) { // #box
- obj = obj || document; //If obj parameter is not passed, document is used by default
- if (param.charAt(0) === "#") //Get element by id name
- return document.getElementById(param.slice(1));//slice here is a function of string, used to get the second element and the string after it
- if (param.indexOf(".") === 0) //< span style = "font family: Arial, Helvetica, sans serif;" > get elements by class name</span>
- return getByClass(param.slice(1), obj);//Call the following getClass function
- return obj.getElementsByTagName(param); // tag
- }
- //How to solve the compatibility problem of getElementsByClassName
- function getByClass(className, obj) {
- obj = obj || document;
After confirming that the browser does not support the document.getElementsByClassName method, the following function adds the child elements of the passed in parent element to an array, traverses it, splits the class names of its elements through spaces (that is, split method), judges the class names, saves the element names containing the required class names into the array result through push(), and finally Return result.
- <span style="white-space:pre"> </span>//If the browser supports this method, it directly calls
- if (obj.getElementsByClassName) //Support the use of getElementsByClassName method
- return obj.getElementsByClassName(className);
- /* The use of the getElementsByClassName method is not supported*/
- //Save the array structure of all found elements
- var result = [];
- //Find out all elements of the descendants of obj object
- var tags = obj.getElementsByTagName("*");
- //Traverse each element
- for (var i = 0, len = tags.length; i < len; i++) {
- //Gets all class names used by the current traversal element
- var classNames = tags[i].className.split(" ");
- //Traverses each class name of the current element
- for (var j = 0, l = classNames.length; j < l; j++) {
- if ( classNames[j] === className ) { //Indicates that the currently traversed element has used the class name to find
- result.push(tags[i]);
- break;
- }
- }
- }
- //Return result set
- return result;
- }