Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding jQuery each loop

Tags:

jquery

each

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?

like image 683
mtwallet Avatar asked Dec 09 '22 05:12

mtwallet


2 Answers

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/

like image 191
Blazemonger Avatar answered Feb 09 '23 22:02

Blazemonger


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

like image 35
Vaibhav Avatar answered Feb 09 '23 22:02

Vaibhav