marc4ndrew
marc4ndrew

Reputation: 41

Jquery: How to find nested ul with if statement

i'm trying to build a navigation. I want to find out if the < li > has a < ul >. If < li > has a < ul > then the < ul > should fadeIn else it should open the link. I was already looking on the web.. couldn't find the perfect solution for my problem.

Here is my markup:

    <nav id="mobile-nav">
        <ul>
            <li><a href="#" title="Nav">Link</a>
                <ul class="second">
                    <li><a href="#" title="Sub Nav">Link 2</a>
                        <ul>
                            <li><a href="#" title="Sub Nav 2">Link 3</a></li>
                            <li><a href="#" title="Sub Nav 2">Link 3</a></li>
                        </ul>
                    </li>
                    <li><a href="#" title="Sub Nav">Link 2</a></li>
                    <li><a href="#" title="Sub Nav">Link 2</a></li>
                </ul>
            </li>
            <li><a href="#" title="Nav">Link</a></li>
            <li><a href="#" title="Nav">Link</a></li>
            <li><a href="#" title="Nav">Link</a></li>
        </ul>
    </nav>

jquery:

$('#mobile-nav').on('click', 'a', function(){

if($(this).parent().has('ul')){
    alert("has ul");
    return false;
} else {
    alert("no ul");
    return false;
}

});

I tested it and it always gave me "has ul".

I also tried this:

if($(this).closest('li').has('ul')){
alert("has ul");
return false;
} else {
alert("no ul");
return false;
}

thanks for the help

Upvotes: 0

Views: 1033

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82241

It should be:

$(this).parent().find('ul').length

Working Fiddle

Upvotes: 3

Colin Bacon
Colin Bacon

Reputation: 15609

If you want to test on a bool then you need to use length

Example

if($(this).parent().has('ul').length){
}

Upvotes: 2

Related Questions