Select div (or other element) that class contains

2019-04-18 17:02发布

问题:

First of all; example of HTML code:

<div class"grap1"> some conetent</div>
<div class"grap2"> some conetent</div>
<div class"grap3"> some conetent</div>
<div class"blabla">some content></div>

And now i want to select divs that class contains "grap" word somewhere is class name (so in this case first three divs). How can i achieve that ?

This is not working: http://api.jquery.com/attribute-contains-word-selector/

回答1:

Use the attribute contains selector:

$('div[class*="grap"]')


回答2:

Depending on your particular use-case, you could try the attribute prefix selector:

var $grapDivs = $('div[class|="grap"]');

It seems from your sample data that "grap" is always prefixing the class, so if that's the case this may be what you want. If "grap" can be anywhere in the class instead of just at the beginning, use *= instead.



回答3:

Use the "attribute contains" selector: http://api.jquery.com/attribute-contains-selector/
The "attribute contains word" selector won't work because, according to the docs, it finds elements where the specified attribute contains the given word delimited by spaces.



回答4:

You want to use the "Attribute contains selector", not the "Attribute contains WORD selector", which is what you linked to.



回答5:

What you're looking for is the "attribute contains selector"

See an example here http://jsfiddle.net/CsvUY/