JavaScript uses HTML class to get HTML elements summary _javascript tips

Source: Internet
Author: User

For JS, I think everyone who just touches it should complain about why there is no way to get an element by class. Although the Getelementsbyclassname () function is already supported by a newer browser, it is not compatible with a lower version of the browser, and it has to be encapsulated in a way that is detached from other libraries.

Method One

function GetByClass1 (parent, CLS) {
  var res = [];  The array containing the matching results
  var ele = parent.getelementsbytagname (' * ');
  for (var i = 0; i < ele.length; i++) {
    if (ele[i].classname = = CLS) {
      Res.push (ele[i])
    ;
  }
  return res;
}

Of course, there is only one value in the class, the above method is fine, but when there are multiple, there will be problems.

<div class= "Test" ></div>
<div class= "Test box" ></div>
<script>
  GetByClass1 (document, ' Test ');  Get only the first Div
</script>

Method Two

When the problem arises, we will try to improve, for the case of multiple names we can use the regular to match whether or not to include the name of the class to find, so there is the following:

function GetByClass2 (parent, CLS) {
  var res = [];
  var reg = new RegExp (' \\b ' + cls + ' \\b ', ' I ');  The matching CLS is a separate word
  var ele = parent.getelementsbytagname (' * ');
  for (var i = 0; i < ele.length i++) {
    if (reg.test (Ele[i].classname)) {
      Res.push (ele[i]);
    }
  return res;
}

This method seems to solve the problem of getByClass1 (), I also used for a long time, but there will be a hidden bug. Look at the following example:

<div class= "Test" ></div>
<div class= "Test_box" ></div>
<div class= "Test-box" ></div>
<script>
  getByClass2 (document, ' Test ');  The result gets the first Div and the third Div
</script>  

In theory, we should only get the first one, but it's not what we expected. This bug comes from the \b in the code below.

var reg = new RegExp (' \\b ' + cls + ' \\b ', ' I ');

Let's take a look at what \b means in the regular.

\b is a special code of regular expressions that represents the beginning or end of a word, the boundary of a word.

Popular Point said: \b is to match a word (from the left boundary to the right border).

And the problem is here, \b, except letters, numbers, underline the other characters as a boundary, for the above example of the third class value of test-box,\b match, the hyphen (-) as a word boundary, so also match the third Div.

Method Three

So we also need to make further improvements to the above methods, which refer to one of the methods mentioned in the StackOverflow:

How do I get the Element by Class in JavaScript?

The improved code is as follows:

function GetByClass3 (parent, CLS) {
  var res = [];
  var reg = new RegExp (' + cls + ', ' I ');  When matching CLS, both sides need to have space
  var ele = parent.getelementsbytagname (' * ');
  for (var i = 0; i < ele.length i++) {
    if (reg.test (' + Ele[i].classname + ')) {
      Res.push (ele[i));
  return
  res;
}

This method to use \b and use a space to match the boundary, first in the classname value to get to add a space on both sides, so as to ensure that each of the values in the classname will have spaces on both sides, and then use the regular to match.

In this way, the problem has not been discovered for the time being, but when used, the spaces within the single quotation mark in the method must not fall.

Method Four

function GetByClass3 (parent, CLS) {
  var res = [];
  var reg = new RegExp (' (^|\\s) ' + CLS + ' ($|\\s) ', ' I ');
  var ele = parent.getelementsbytagname (' * ');
  for (var i = 0; i < ele.length i++) {
    if (reg.test (Ele[i].classname)) {
      Res.push (ele[i]);
    }
  return res;
}

The blanks are completely treated with regular, which eliminates the problem that the spaces fall easily, and the code is more elegant and concise.

So this method is more perfect, but it is not, below to see the better plan.

Method Five (Perfect edition)

As mentioned at the beginning of the article, the Getelementsbyclassname () method is already supported by the newer browsers. For performance reasons, it's definitely better to use native methods for supported browsers. For a lower version of the browser, use the above method four.

function Getbyclass (parent, CLS) {
  if (parent.getelementsbyclassname) {return
    parent.getelementsbyclassname (CLS);
  } else{
    var res = [];
    var reg = new RegExp (' + cls + ', ' I ')
    var ele = parent.getelementsbytagname (' * ');
    for (var i = 0; i < ele.length i++) {
      if (reg.test (' + Ele[i].classname + ')) {
        Res.push (ele[i));
    }
    return res;
  }

Of course, method Five is considered to be a relatively good solution, if there are better ways to welcome the message added.

Related Article

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.