Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
For each div that has li, add class

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>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

also ID must be unique

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!