Reputation:
I'm using jQuery to achieve the following:
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>
Upvotes: 0
Views: 97
Reputation: 37
$('#general-block > ul').each(function() {
if ($('general-block:has(li)').length) {
$('general-block').addClass('testing-block');
}
});
also ID must be unique
Upvotes: 0
Reputation: 419
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.
Upvotes: 1
Reputation: 1
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>
Upvotes: 0