4

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?

3 Answers 3

9

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2
$('.sectionInner').each(function(i) {
    if ($('div', this).hasClass('carousel')) {
        alert('We got a Carousel!');
    }
    else {
        alert('No Carousels here')
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.