Search code examples
jqueryhtmlmobilemenudisable-link

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


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();

Solution

  • 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').....