Use native JavaScript to simulate getelementbyclassname.

Source: Internet
Author: User

Recently at work, because a plugin must use Jquery-pack.js, and this package is very old jquery, so the function is not used, such as the $ () selector and the parent () can not get the contents of the label.

So there is no way, only native JavaScript, in order to achieve this function, I have to use the HTML tag class to get the DOM structure of the tag.

In JavaScript built-in core, the document object and the element object can be in a total of three ways to obtain the following elements, namely: getElementById (' id '), getelementsbyname (' name '), getElementsByTagName (' tag ').

However, when designing a Web page, the class that most often needs to be used does not have a corresponding method to get the same classname elements.

But we can write one ourselves, the code is very simple:

function Getelementsbyclassname (tagname,classname) {        var tag = document.getElementsByTagName (tagName);        var tagall = [];        for (var i = 0; i<tag.length; i++) {            if (Tag[i].classname.indexof (className)! =-1) {                tagall[tagall.length] = ta G[i];            }        }        return tagall;    }


The principle is to get the contents of the tag by getting the specified label, using getElementsByTagName to obtain the content of the label, and then comparing it to the parameters passed in according to the classname of the label, and then returning it if the equality is placed in the array.

Use native JavaScript to simulate getelementbyclassname.

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.