Phill
Phill

Reputation: 546

jQuery - selecting previous element link

I can't see why this isn't working. I have a list, each item has a background image on the anchor. With jQuery I'm trying to remove the background image on the item right before the selected anchor. Here is the HTML:

<ul id="menu">
<li class="last"><a href="#">Contact Us</a></li>
<li><a href="#">Testimonials</a></li>
<li><a href="#">Projects</a></li>
<li class="selected"><a href="#">Our Services</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Home</a></li>
</ul>

And here is the jQuery I am using to try and remove the background image (using display:none for testing purposes):

$('li.selected a').prev().css( {display : "none"});

When I use the following, it works:

$('li.selected').prev().css( {display : "none"});

But as soon as I involve the anchor tag, it stops.

TLDR: Basically I need to select "projects" which is before the selected link, and remove its background image tied to it (to the link, not the list item). Can anyone tell me why that code isn't working?

Thanks

Upvotes: 1

Views: 1009

Answers (2)

j08691
j08691

Reputation: 207861

The <a> link in $('li.selected a') has no previous element. It's alone as a child of the list element. You would need to go up one level in the DOM to the <li> and then use .prev.

Like $('li.selected a').parent().prev().css( {display : "none"});​

jsFiddle example

Or for your specific need:

$('li.selected a').parent().prev().children('a').css( {backgroundImage : "none"});​​​​​​​​​​​​​​​

Upvotes: 1

Austin
Austin

Reputation: 6034

.prev(0) and .next() select from the previous and next siblings of the selected element, respectively. For your purposes, this will work:

$('li.selected').prev().find("a").css( {display : "none"});

Upvotes: 1

Related Questions