How to find if LI has children UL
This is what you looking for
$('li:has(> ul)');
Js Fiddle Demo
use the :has selector
like
$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function () {
if ($(this).closest('li').has('ul').length) {
alert("yes");
} else {
alert("no");
}
});
In your specific code, it looks like you need to use this
to refer to the element that was clicked on and then find the parent <li>
from there so you are operating on only the <li>
that had the click in it:
$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function() {
if($(this).closest("li").children("ul").length) {
// the clicked on <li> has a <ul> as a direct child
}
});
In jQuery, you can use either .find("ul")
or .children("ul")
depending upon whether you're looking for only immediate descendants or any descendant.
For example, if you want to find out if a particular <li>
tag that you already have a reference to has a <ul>
as a direct child, then you can do this:
if ($(el).children("ul").length) {
// el has a ul as an immediate descendant
}
Or, if the ul can be any descendant, then you can use this:
if ($(el).find("ul").length) {
// el has a ul as a descendant at any level
}
If you want to just find all the <li>
tags with <ul>
below them, then you have these two options:
You can get a list of all <li>
tags with a <ul>
anywhere inside of it like this:
var tags = $("li").filter(function() {
return $(this).find("ul").length !== 0;
});
If you only want immediate descendants, you can use this:
var tags = $("li").filter(function() {
return $(this).children("ul").length !== 0;
});
You can then operate on those particular <li>
tags by just calling a method on the jQuery object without using the if
:
var tags = $("li > ul").addClass("hasSubMenu");