Getting an element using jquery with similar class names
I have a 2 div tags which a similar class names, the only difference is that the second div has an extended class name. How can I retrieve the 2 elements seperately in 2 different variables using jquery.
<div class='container'>
<div class='submit'></div>
<div class='submit newClass'></div>
</div>
From the above example I need the item which has the class 'submit'
and not 'submit newClass'
.
If i did $('div.container .submit')开发者_StackOverflow社区
, this gives me both the div tags. How can i acheive this. I would not like to use index based selections or by using the 'first'
method in jquery.
In your example, the second div
does not really have an "extended class name" as you put it, it has two separate classes, submit
and newClass
. If that's the case, you can exclude elements matching .newClass
from your selection using the :not
pseudo-selector:
var elements = $(".submit:not(.newClass)");
Alternatively, you could use the not
method:
var elements = $(".submit").not(".newClass");
If on the other hand your example is wrong and you do actually have an longer class name that starts with "submit", you can use the "contains word" selector:
var elements = $("[class~=submit]");
Use :not
with the class you don't want:
$('div.container .submit:not(.newClass)')
精彩评论