How is it possible to get the number of divs, which are in a li element.
Here is my code but it doesn't work. (Doesn't work mean every img gets the class, also when there is just 1 div inside the li.)
if($('.lookbook ul li').find('div').length > 1){
$('.lookbook ul li img').addClass('lbcursor');
}
here is my html structure:
<div class="lookbook>
<ul>
<li>
<div><img/></div>
<div></div>
</li>
<li>
<div><img/></div>
<div></div>
</li>
<li>
<div></img></div>
</li>
</ul>
</div>
the third img shouldn't get the class.
i want the number of divs in the li element and if there are more than 1 divs it should add the class .lbcursor to the img.
i did find a similar answer here : jquery: if children with specific class? but it doesn't work
ah i just recognized, that the if clause is correct. the problem is to which elements i add the class.
Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.
grab the second child: $(t). children(). eq(1);
html - div not allowed as child element of button - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
You need to loop through, and target that element.
$('.lookbook ul li').each(function() {
var $this = $(this);
if ($this.find('div').length > 1) { //if looking for direct descendants then do .children('div').length
$this.find('img').addClass('lbcursor');
}
});
Fiddle
You can also write this as:
$('.lookbook ul li').each(function() {
var $this = $(this);
$this.find('img').addClass(function(){ //using function argument syntax for addClass
return $this.find('div').length > 1 ? "lbcursor" : "";
});
});
Clean and simple using the :has() and the :nth-of-type() selectors.
$('.lookbook ul li:has(div:nth-of-type(2)) img').addClass('lbcursor');
jsFiddle Demo
:nth-of-type()
selector, this would work only if the div
elements are the direct children of the same element (as seen in your question).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With