Check if a list has an ul element as a child

Hi,

please I would to receive some help to my question:
I want to add a background-image (an arrow) within an anchor <a> only if his parent <li> has <ul> as a child.

But when I load the page, appears that background, in every anchor of the page.
Below there is the code, the commented lines in the js file are my other attempts, that I think logically correct, with no success! Where is the error?

here is my html:


<nav>
   <ul id='nav'>
      <li><a href=''>Link 1</a></li>
      <li><a href=''>Link 2</a>
         <ul>
            <li><a href=''>child-link1</a></li>
            <li><a href=''>child-link2</a></li>
         </ul>
      </li>
   </ul>
</nav>

and this is my included js:

   // if ( $( "#nav li" ).length ) {
   // if ( $( "#nav li" ).find("ul").length ) {
   // if ( $( "#nav li" ).children("ul").length) {
   if ( $( "#nav li" ).parent().children("ul")) {
   // if ( $( "#nav li:has(>ul)" ) ) {
      var styles = {
         "background-image" : "url('include/arrow_down.png')",
         "background-repeat" : "no-repeat",
         "background-position" : "right center"  
      };
      $("a", this).css(styles);
   }

I hope I have been clear, can you help me please?
many thanks!

Hi,

You can do it like this:

$("#nav li a").each(function(){
  if($(this).parent().children("ul").length){
    $(this).addClass("expandable");
  }
});

And use a class instead of inline CSS:

.expandable{
  background-image: url('include/arrow_down.png');
  background-repeat: no-repeat;
  background-position: right center;
}

Thanks! So, where is the error in my script? Do I have to use necessarily a loop for the success of the purpose?

Simply, this should help…


var parentItem = ($('#nav ul').length >0);
$("#nav li a").each(function(){
  if($(parentItem) {
    var childItem = $(this).children("ul li");
    $(this).addClass("expandable");
     }
});


Ok thanks! But, now I continue to wonder why to put an “each” within the script. Do the parent() and children() methods acts on entire document (also without the use of a loop), filtering results by a selector?

You need to select all of the appropriate anchor tags, then examine each of them to determine whether they meet the criteria you are searching for (the parent <li> has <ul> as a child).

One way of doing this is using $.each.
You could also use a for loop.

1 Like