简体   繁体   中英

how to find element in div which has Class and is NOT this in jquery

I'm trying to find an element in div called wrapper which has a class of active 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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM