开发者

jQuery selector for a class followed by a space and then again another class

I have a markup like this:

<div class="classA classB">the content</div>

What I would like is a selector that selects all of the divs that start with classA and I did this:

$("div[class^='classA'");

but since I (for example) have also classes like:

<div class="classAsuffix">

that selector would grab this div also, and I do not want that.

So, I want a selector that will get me all of the divs that do start with classA but then after that have a space so in general: give me all divs which have "classA (space) someOtherClass".

I hope I'm clear with my request. Thank you for your help!

Oh, forgot tot mention: I tried this:

$开发者_如何学Python("div[class^='classA ']") but it doesn't work...


The quotes around your value should be double quotes, not single quotes. Actually, it doesn't seem to matter. So:

var matches = $('div[class^="classA "]');

...which works with the latest jQuery. It matches an element with a class attribute starting with "classA " and so doesn't match div class="classA" but does match div class="classA classB". But your version with single quotes works too. I've tried Chrome 11 (Linux & Windows), Firefox 3.6 (Linux), Firefox 4.0.1 (Windows), IE6, IE7, IE9, Opera 11 (Linux & Windows), and Safari 5 (Windows). I've tried jQuery 1.6.1 (the links above are to the "latest"), and jQuery 1.5.2. All gave the same result, finding only what I understand you want it to find.

But — and this is slightly off-topic — I'd take a step back and look hard at why this need is coming up. It's very unusual, which suggests there may be a better approach... Without knowing the underlying need, though, I could be wrong there.


you could combine two statements.

$("div[class^='classA'].classA");

This case you would check for class beginning with classA and also that the element has this class. But this would also be valid class="classASuffix classA classB" or class="classA".


This should get all DIVs with class="classA classB":

$("div[class^='classA'][class$='classB']");

Selects all DIVs where the class-attribute STARTS WITH 'classA' and ENDS WITH 'classB'

http://jsfiddle.net/9dQ9Z/


you can use $('div[class~="classA"]'); See the following link for explanation: http://api.jquery.com/attribute-contains-word-selector/


This would select all divs that have both classA and classB, but not divs with just classAsuffix and classB:

$('div.classA.classB');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜