0

I'm trying to loop through a multidimensional array. I want to remove the class "list" when it is in one of the div in my array. But it is possible that there is more than just one div with this class on my site.

So I tried to resolve that with two for-loops but I get it didn't work.

const $lists = [
                $('.first'),
                $('.third')
            ];

var i, j;
for (i = 0; i < $lists.length; i++) {
    for (j = 0; j < $lists[i].length; j++){
        $lists[i][j].find(.list).removeClass(list);
    }
}
.list {
  background: green;
}
<div class="first">
  <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="first">
  <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="second">
   <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="third">
   <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

I also tried it with CSS and :not[]. But that didn't work too.

.

 .list:not(.first)  {
     border: 3px solid red; }
1
  • classnames should be enclosed in quotes. .find(".list").removeClass("list"); Commented Oct 26, 2017 at 10:02

2 Answers 2

1

Combine the selected divs by to one by applying jQuery.merge(), find all items that contains the .list class, and remove it:

And if you want to remove it just from first and third:

var $lists = [
    $('.first'),
    $('.third')
];

$($.merge.apply([], $lists)).find('.list').removeClass('list');
.list {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
  <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="second">
   <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="third">
   <ul class="list">
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

$(document).ready(function(){
$(".second").not(".first, .third").addClass("list")
});
.list {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="first">
  <ul>
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="second">
   <ul>
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

<div class="third">
   <ul>
    <li>foo</li>
    <li>fooooo</li>
    <li>bar</li>
  </ul>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.