terinjokes
terinjokes

Reputation: 355

How to select a:hover that's not in a certain selector

I would like to style a elements that are not in a certain id. For example, let's say this is my HTML:

<div id="boat">
   <a href="#">I'm in a boat! ☻</a>
</div>
<a href="#">☹</a>

Now, let's say I only want to style the a element that's not in a boat. I expected something similar to a:hover:not(#boat a) to work, but alas, it doesn't. Is there a way I can do what I want to do?

Upvotes: 0

Views: 693

Answers (3)

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

When it comes to jQuery selectors a:hover will select all the a elements which have the CSS pseudo class :hover applied to it (i.e. a elements which are currently being hovered over with the mouse).

This is the selection process, and not the styling selection, to select the elements you are talking about, try this instead:

$('a:not(#boat a)')

DEMO: http://jsfiddle.net/marcuswhybrow/AMWhU/

If a hover jQuery effect is waht you are after the once you have made the selection just bind the event as usual:

$('a:not(#boat a)').hover(function() {});

Upvotes: 3

Kyle Burton
Kyle Burton

Reputation: 27528

It looks like you can use a negating attribute selector ('!='). Given (mostly) your original html:

<script src="/Users/kburton/Downloads/jquery-1.4.4.min.js">
    </script>
<div id="boat">
  <a href="#">I'm in a boat!</a>
</div>
<div id='car'>
  <a href="#">I'm in a car!</a>
</div>
<a href="#">I'm not in the boat!</a>

At the javascript console, running:

$('[id!="boat"] > a')

Looks for all nodes that do not have the id 'boat', with an anchor child.

Upvotes: 0

mVChr
mVChr

Reputation: 50177

Links not within that div#id will have .closest('div#id').length === 0, and since 0 is false, you can select on the opposite of those as follows to style those links:

$('a').hover(function(e){
    if (!$(this).closest('div#boat').length) {
        // YOUR CODE HERE
    }
});

Here's an example.

Upvotes: 0

Related Questions