views:

49

answers:

2

Suppose I have the following

<ul>
<li>Item 1</li>
<li>Item 2
   <ul>
    <li>Sub Item</li>
   </ul>
</li>
<li>Item 3</li>
</ul>

This list is auto-generated by some other code (so adding exclusive id's/class' is out of the question. Suppose I have some jquery code that states that if I mouseover an li, it gets a background color. However, if I mouseover the "Sub Item" list item, "Item 2" will be highlighted as well. How can I make it so that if the user mouses over "Sub Item" it only puts a background color on that and not on "Item 2" as well?

I also forgot to mention that I already have something like $("li").doSomething... on the page already...

A: 

try $('ul li li') as your selector. IE

ul li li:hover {background:#00F;}

EDIT

For a JQuery solution, it's the same selector. IE

`$('ul li li').css('background','#00F');

edl
+2  A: 

First you'll need a bit of CSS, a hover class and a background on the <li> elements, so the parent's background doesn't show up on children (because otherwise they have a transparent background, so whatever the parent has will show), like this:

​.hover { background: #ddd; }
li { background: #fff; }

Then you can use mouseover and mouseout (not mouseenter and mouseleave like .hover() uses), like this:

$('li').mouseover(function(e){
    $(this).addClass("hover").parents().removeClass("hover");
    e.stopPropagation();
}).mouseout(function(){
    $(this).removeClass("hover");
});​

You can see a working demo here. This uses .mouseover() and .mouseout() (so it fires when entering/leaving a child element, which mouseenter/mouseleave specifically won't). On hover we apply the hover class to the current <li> and remove the class from any parents that might have it. Also we prevent the event from bubbling with event.stopPropagation() so the same thing doesn't happen on this element's parents...just comment this out in the demo to see how this affects things :)

Nick Craver
+1 - I got the question completely wrong. Here's a fiddle with your code http://jsfiddle.net/5LRKL/3/ for demonstration purposes
Ben
@Ben - Thanks, I linked a fiddle in the question though :) I usually try to whenever it's demo-able :)
Nick Craver