Get each <li> with child <div> and change the <li>'s <a> attribute

1.1k views Asked by At

I'm disabling the links in my menu and turning them into accordion type buttons. some links don't have children though (dropdowns if you will), and I'd like those to stay as links.

I want to target each LI with a child Div and change that Li's a=href value I've done that, but i specifically don't want to change any Li's a=href value IF it doesnt have a child Div in the first place.

Here is my code:

$(window).on("resize", function() {
        $(function() {
            if ($(window).width() <= 900 & $( 'div.menu-main-menu-container > ul.main-menu > li.menu-item > a' ).attr( 'href' ) != "#") {
                $( 'div.menu-main-menu-container > ul.main-menu > li.menu-item > a' ).each(function() {
                    var old = $(this).attr( 'href' );
                    $(this).attr( 'data-href', old);
                    $(this).attr( 'href', '#');
                });
            } if ($(window).width() > 900 & $( 'div.menu-main-menu-container >     ul.main-menu > li.menu-item > a' ).attr( 'href' ) == "#") {
                $( 'div.menu-main-menu-container > ul.main-menu > li.menu-item >     a' ).each(function() {
                    var old = $(this).attr( 'data-href' );
                    $(this).attr( 'href', old);
                });
            }
        });
}).resize();
3

There are 3 answers

0
ChrisV On BEST ANSWER

You can select only the li's with child divs with the jQuery has method, for example like this:

$('div.menu-main-menu-container > ul.main-menu > li.menu-item').has('div').children('a').....
2
A.J. On

You can do this:

if ($('li').children().length > 0)
{
    //do something
}

Or alternatively:

if ($('li').children().length == 0)
{
    //do something else
}

Also, it seems that you aren't looping through the li's (otherwise I would've suggested using $(this)). There's definitely a better way to accomplish selecting these elements. You have such long strings for the selectors (i.e. 'div.menu-main-menu-container > ul.main-menu > li.menu-item > a' ) where you can probably reduce to a simple unique class or id.

0
xiongbo027 On

you can choose that li which first element is div like this:

$('li > div:first').each(function(){
  $(this).parent('li')
  ......
});

hope this can help you :)