Home > Mobile >  Js Dom: Find an element where the class is similar to, or includes substring
Js Dom: Find an element where the class is similar to, or includes substring

Time:07-19

I have a specific wrapper element where the class has a specific name included, alongside with a random id. Example wp-rgtayfu-fxyjzw-wrapper. The class will always contain the wrapper substring. There is only one element in the document where the class contains wrapper.

How can I find it? (Or how can I query an element by class, using only a substring part of it?)

CodePudding user response:

you can use this CSS Selector.

[attribute*="value"]

It will select element with a class attribute that contains the specified "value":

const targetElement = document.querySelector('[class*="wrapper"]')

CodePudding user response:

It is better to separate the part of class you need using space. It will appear separately in classList property and document.getElementsByClassName can find it

The resulting class will be wp-rgtayfu-fxyjzw wrapper or wp rgtayfu fxyjzw wrapper

If you dont want to change the class, you can run a regex through the entire DOM, but it is really bad idea.

  • Related