I have the following code:
HTML:
<div class="sectionInner"><div class="carousel"></div></div>
<div class="sectionInner"></div>
<div class="sectionInner"></div>
<div class="sectionInner"></div>
JS:
function checkForCarousel() {
$('.sectionInner').each(function(i) {
if($(this).has('.carousel')) {
alert('We got a Carousel!');
}
else {
alert('No Carousels here')
}
});
}
checkForCarousel();
What I am trying to do is loop over the four div.sectionInner if I find a child with class of carousel then I want to append some buttons. I know I can just target the carousel directly but this is part of a bigger picture and I do have a reason for wanting to use a loop.
Anyway as the loop begins it alerts 'We got a Carousel' as you'd expect for the first div. It then carries on alerting 'We got a Carousel' when quite clearly we don't have Carousels for the other three divs. What am I doing wrong here?
It's because you're testing for the existence of a jQuery object, which is always true
. You need to test for length > 0
instead:
if($(this).has('.carousel').length) { // is false if length == 0
http://jsfiddle.net/mblase75/DzafK/
This is the classic case of "truthy" and "falsey" values in javascript. You will notice that $(this).has('.carousel') will return an object. Objects are always truthy in javascript. Please refer the following link:
http://james.padolsey.com/javascript/truthy-falsey/?utm_source=javascriptweekly&utm_medium=email
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