tags:

views:

26

answers:

3

Hello, I have a situation where I need to identify if a list element (li) has a sub (ul) underneath it, and if it does, I need to change the background image of the anchor tag (a) under the (li) to display a sub-menu indicator image (say subMenuImg.gif). All the anchor tags (a) have a css class of "menuLink", if there is a sub-menu for that list element (li), I would like to change it to subMenuLink. I can then apply the styles on this sub-menu link as needed.

How can I best do it with jQuery?

A: 

I'm not sure what you mean by "dynamically", but adding a class to a link is easy.

$('li').addClass('menuLink');

Although the real question is how you're going to be handling everything else, and without more information, I can't begin to elaborate on that.

BBonifield
A: 

You could get a list of li with ul underneath it with:

$("li:has(ul)")

Then you can apply a different style to each immediate child of the li with

$(this).find(">a").addClass("hasSubmenu");

Put it all together like this.

$("li:has(ul)").each(function(){
    $(this).find(">a").addClass("hasSubmenu");
});
skajfes
Thank you for this answer! Both the above answers worked. But yours is the best option in my scenario. I tried adding code, but unfortunately for me, the <code> and <pre> blocks didn't quite work so I had to try and make the best using text fields. Thanks again!
Anup Marwadi
I am just glad to help.
skajfes
A: 
//loop ul that is a direct children of an li
$("li").children("ul").each(function(){
  //find the a of the parent (in this case the parent is li) since $(this) refers to the ul
  $(this).parent().find("a")
  //change the background image of the said "a"
  .css("background-image","subMenuImg.gif");
  //remove the class of the "a" and add a new class
  .removeClass("menuLink").addClass("subMenuLink")

});

Hope that helps. I'm just wondering why you have to add the background image manually when you can just let's say

.menuLink{}
.subMenuLink{ background-image:url('subMenuImg.gif'); }
xar