KulerGary
KulerGary

Reputation: 217

Targeting Only the Parent 'li' and ignoring Other CHildren 'li's'

I know that I am close to getting this sorted but I am sure there is a better way to achieve the following:

I want to target 'li's' that have a child 'ul' and append a span like this:

<li class="parent">
 <a>Item 1 <span> </span></a>

  <ul>
    <li></li>
    <li></li>
  </ul>
</li>

Here is the jQuery I am trying to use:

jQuery(document).ready(function(){
jQuery('ul').attr("id", "nav");
jQuery("ul#nav li:has(ul)").addClass("hasChildren");    
if (jQuery('ul#nav li.hasChildren').length)
{
    jQuery('ul#nav li.hasChildren a').append("<span></span>");
}
});

The problem is that a span gets added to all of the 'li's' regardless if they have a sub ul in them or not.

So my question is how to add a span to ONLY the li's that have a sub ul in them and not to all of the li's

Gary

Upvotes: 1

Views: 1417

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

The issue in your code is with this selector ul#nav li:has(ul). It will look for all the li elements inside ul#nav. If you want to just look for the child elements then you should use ul#nav > li:has(ul). Try this

jQuery(document).ready(function(){
   jQuery('ul:first').attr("id", "nav");
   jQuery("ul#nav > li:has(ul)").addClass("hasChildren");    
   if (jQuery('ul#nav li.hasChildren').length)
   {
       jQuery('ul#nav li.hasChildren a').append("<span></span>");
   }
});

Simplified version of your code.

jQuery(document).ready(function(){
   jQuery('ul:first').attr("id", "nav");
   jQuery("#nav > li:has(ul) li").append("<a>...<span>..</span> </a>");
   }
});

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99997

The ul#nav li.hasChildren a selector is selecting all descendant a elements. If you just want to select for direct child elements, use ul#nav li.hasChildren > a.

Upvotes: 1

Chriszuma
Chriszuma

Reputation: 4558

Try this:

$("li ul:first").before("<a>Item 1 <span> </span></a>");

It will select the first ul in each li, and add that text right before it.

Upvotes: 0

Related Questions