When we first approached JavaScript, we found some constant selectors in the document, such as: Document.getelementbyid,document.getelementsbytagname,document.getelementbyname,document.getelementsbyclassname and so on. In practical applications, I think the usual selector is the ID selector. Class selector, Tag Selector.
However, when we come into contact with jquery, we are accustomed to using the $ (' xxxx ') selector to get DOM elements.
When we use native JavaScript, we feel that each time we use these selectors, there will be a long string of code. Again here, I myself encapsulated a universal jquery-style fetch way to get DOM elements in native JavaScript.
Gets the ID of the incoming #+id //Get class passed in. +class //Gets the label incoming tag name function $ (obj) { var which = obj.substr (0, 1); var newName =obj.split (which) [1]; if (which== ' # ') { return document.getElementById (newName); } else if (which== '. ') { return document.getelementsbyclassname (newName); } else{ return document.getelementsbytagname (obj); } }
Here, we find that this method differs little from the jquery selector. When we want to use the ID selector, we just need to call $ (' #id '), you can. Class, Call $ ('. class ') when the tag is called, and then call $ (' P '). It's very convenient and quick for children's shoes that are used to jquery.
Here, we can also pass Document.queryselector (' #id | | | class| | TagName ') to get the DOM element.
Native JS Implementation Basic Selector