Reputation: 43
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');
}
});
Upvotes: 1
Views: 3760
Reputation: 69915
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');
}
})
Upvotes: 0
Reputation: 150273
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.
Upvotes: 1
Reputation: 29498
$('#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');
}
})
Upvotes: 1