Home > Blockchain >  For each div that has li, add class
For each div that has li, add class

Time:02-17

I'm using jQuery to achieve the following:

  • For each div with the same id, check to see if the div has any li elements. If it does, then add a specific class.

The code below only works for one of the divs. What do I change so that it loops through all instances of div with the same id.

$('#general-block').each(function() {
   if ($('general-block:has(li)').length) {
      $('general-block').addClass('testing-block');
   }
});

// The class 'testing-block' should be added to the first two divs with the id 'general-block' as they have li elements.
<div id='general-block' class='block'>
   <ul>
      <li>Test</li>
      <li>Test</li>
   </ul>
</div>

<div id='general-block' class='block'>
   <ul>
      <li>Test</li>
      <li>Test</li>
   </ul>
</div>

<div id='general-block' class='block'>
   <p>Class won't apply to the parent div</p>
</div>

CodePudding user response:

You can't have multiple elements with the same id,ID must be Unique

you can use .each via class , and Add Custom Class for any div has li

$('.general-block').each(function() {
   if ($(this).children().find('li').length>0) {
      $(this).addClass('testing-block');
   }
});



    <div class='general-block block'>
   <ul>
      <li>Test</li>
      <li>Test</li>
   </ul>
</div>

<div class='general-block block'>
   <ul>
      <li>Test</li>
      <li>Test</li>
   </ul>
</div>

<div  class='general-block block'>
   <p>Class won't apply to the parent div</p>
</div>

CodePudding user response:

As was specified previously, you can't have several elements with the same id, ID must be unique.

However, it is totally possible to add a class if the element has a specified child.

$(".block:has(li)").addClass('testing-block');

A class selector will return all of the matches. The Id just the first one. All elements matches is what would work nicely here.

But again for unique elements use different IDs.

CodePudding user response:

$('#general-block > ul').each(function() {
   if ($('general-block:has(li)').length) {
      $('general-block').addClass('testing-block');
   }
});

also ID must be unique

  • Related