Get all items that start with class name

后端 未结 5 1367
[愿得一人]
[愿得一人] 2020-12-17 00:30

I\'m trying to only show certain divs. The way I have decided to do this is to first hide all elements that start with \"page\" and then only show the correct <

5条回答
  •  清歌不尽
    2020-12-17 00:34

    getElementsByClassName only matches on classes, not bits of classes. You can't pass a regular expression to it (well, you can, but it will be type converted to a string, which is unhelpful).

    The best approach is to use multiple classes…

    i.e. This div is a page, it is also a page1.

    Then you can simply document.getElementsByClassName('page').


    Failing that, you can look to querySelector and a substring matching attribute selector:

    document.querySelectorAll("[class^=page]")
    

    … but that will only work if pageSomething is the first listed class name in the class attribute.

    document.querySelectorAll("[class*=page]")
    

    … but that will match class attributes which mention "page" and not just those with classes which start with "page" (i.e. it will match class="not-page".

    That said, you could use the last approach and then loop over .classList to confirm if the element should match.

    var potentials = document.querySelectorAll("[class*=page]");
    console.log(potentials.length);
    elementLoop:
      for (var i = 0; i < potentials.length; i++) {
        var potential = potentials[i];
        console.log(potential);
        classLoop:
          for (var j = 0; j < potential.classList.length; j++) {
            if (potential.classList[j].match(/^page/)) {
              console.log("yes");
              potential.style.background = "green";
              continue elementLoop;
            }
          }
        console.log("no");
        potential.style.background = "red";
      }
    Yes
    No
    Yes
    Yes
    Yes
    Unmatched entirely

提交回复
热议问题