how to find element in div which has Class and is NOT this in jquery
Solution 1
Please note that your html is invalid, DIV
can not be a child of UL
. Selector is not correct either using $('.title')
since it is not the class that you are applying active to
hasClass()
returns a boolean, so is not chainable
Not exactly sure what you are trying to do but based on code shown you need to use the not()
filter before hasClass()
:
if ($("#wrapper ul li").not(this).hasClass("active")) {
OR
if ($("#wrapper ul li.active").not(this).length) {
If all it is for is to remove the class, simply remove the active class from all before adding to the current one and you don't need to test for it first
Solution 2
Using not
works fine to exclude an element:
$('#wrapper li').click(function(){
$('#wrapper li').not(this).removeClass('active');
$(this).addClass('active');
});
Demo: http://jsfiddle.net/97DXe/
If you comment out the addClass, you will see that clicking the already active element doesn't remove the class from it.
If you are going to set the active class on the clicked element, it doesn't do much harm to simply remove the class from all the elements first, so then you wouldn't need the not
.
Related videos on Youtube
Ricki
Updated on September 15, 2022Comments
-
Ricki over 1 year
I'm trying to find an element in div called
wrapper
which has a class ofactive
but is not the one I've just clicked.Here is my code which works if I click on the
.title
class:$(".title").click(function(){ if ($("#wrapper ul li").hasClass("active")) { alert("found one!"); } });
But i have no idea how to check if its not the one I've clicked. I tried adding
.not(this)
and.not($(this))
to my if statement to no avail.I should add i plan to
removeClass
of any that are not the current selected div.I'm sure I have something wrong somewhere.
for reference heres the HTML:
<div id="wrapper"> <ul> <div class="title">Title</div> <li class="active">Active Clicked List Item</li> </ul> <ul> <div class="title">Title</div> <li>Some Other List Item</li> </ul> <ul> <div class="title">Title</div> <li>Some Other List Item</li> </ul> </div>
Any Suggestions on how I can do this?
-
Ricki about 11 yearsWorks great. Upon seeing this i modified my html and jQuery. I have some bad practises. Thanks!!