Question

I am trying to run some javascript (toggleClass) only if the clicked menu link has a submenu. Is this possible? Thanks in advance for your help.

$('#nav a').click(function () {
    if (???) {
        $(this).toggleClass('sf-js-enabled');
    }
});

No correct solution

OTHER TIPS

$('#nav a').click(function () {
    // Proceed only if children with your submenu class are present
    if ($(this).find('.submenuClass').length > 0) {
        $(this).toggleClass('sf-js-enabled');
    }
})

Use the has selector:

$('#nav a:has(.submenu)').click(function () {
        $(this).toggleClass('sf-js-enabled');
    });

This way jQuery will traverse the DOM only once, and not on each click like in all the other answers you got.

has docs:

Description: Selects elements which contain at least one element that matches the specified selector.

Try this.

$('#nav a').click(function () {
    if ($(this).find('submenuSelector').length) {
        $(this).toggleClass('sf-js-enabled');
    }
})

Alternatively you can use has(selector) method which reduces the set of matched elements to those that have a descendant that matches the selector or DOM element.

$('#nav a').click(function () {
    //Do other suff here

    if ($(this).has('submenuSelector').length) {
        $(this).toggleClass('sf-js-enabled');
    }
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top