Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add class to all siblings except 1

Tags:

jquery

I've got a list like this:

<ul id="items"><li><a href="">Link</a></li><li><a href="">Link</a></li><li class="divider"></li><li><a href="">Link</a></li><li><a href="">Link</a></li></ul>

When I click any of the anchors I want to add a class to all the li's except for the parent of the link that I clicked and the li with the "divider" class.

I can get it to work with all the siblings with this:

 $(this).parent().siblings().attr("class", "transparent");

So how do I get it to ignore the li with the "divider" class?

Thanks very much.

like image 593
Daelan Avatar asked Jan 24 '11 20:01

Daelan


Video Answer


1 Answers

You can also use the .not command to filter out anything from a set that you don't want. This is an alternative to passing in a CSS :not pseudo class selector as mentioned by Matt.

$(this).parent().siblings().not(".divider").addClass("transparent");

Also it's probably better to use .addClass and .removeClass

Edit:

jQuery is bad, use DOM ;)

link.addEventListener("click", function addClasses() {
    var li = this.parentNode,
        lis = li.parentNode.children;

    [].forEach.call(lis, function addClassIfCorrect(el) {
        var classList = el.classList
        if (el !== li && !classList.contains("divider")) {
            classList.add("transparent");
        }
    });
});
like image 145
Raynos Avatar answered Sep 30 '22 13:09

Raynos