Native JS Implementation Basic Selector

Source: Internet
Author: User

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

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.