If Element has Child Then.... Jquery Question

OK I have this HTML.

<div class="sidebar">

Now with Jquery I want to auto detect that if an ul li has child ul then add a class to its parent li.

I did this

if($(".sidebar ul li").has("ul")) {
		$(this).append('<span class="ddicon"></span>');

but no effect. Can anybody help please? Thank you.

Edit: I tried different codes but sometime it adds the class ddicon to all li’s i.e which dont have any ul also.

Any reason you’re doing it that way instead of using the selector?

$(".sidebar ul li ul").parent().addClass("ddicon");

Hi Dave, What do you mean by “instead of using the selector?” Please explain.

In otherwords, why use an if statement if it’s not needed…

jQuery uses the css selector syntax - the part inside the $(). You just need to apply the appropriate css selector to find what you want. The line of code I gave you looks for the same element you’re asking for (the ul inside another ul), finds it’s parent element, then gives it a class of ddicon.

I see. OK Thank you Dave. Your solution helped.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.