Get all items that start with class name

后端 未结 5 1365
[愿得一人]
[愿得一人] 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:33

    Previous answers contain parts of the correct one, but none really gives it.

    To do this, you need to combine two selectors in a single query, using the comma , separator.

    The first part would be [class^="page"], which will find all the element whose class attribute begins with page, and thus not viable for elements with multiple classes, which is fixed by [class*=" page"] which will find all elements whose class attribute have somewhere the string " page"(note the space at the beginning).

    By combining both selectors, we have our classStartsWith selector:

    document.querySelectorAll('[class^="page"],[class*=" page"]')
      .forEach(el => el.style.backgroundColor = "green");
    Yes
    No
    Yes
    Yes
    Yes
    Unmatched entirely

提交回复
热议问题