1

How would I go about selecting a child element of a previous element. I know how to select the previous element using .prev(), but how do I selected the child element of that previous element so that I can modify the CSS? Thanks for any help.

jQuery:

$("li.selected").prev().css("border-right", "none");

EDIT:

I would like only the element before the element with the "selected" class to have css style applied to it. Currently all elements are having the css selector applied. Thanks.

<ul id="nav_1510737">
    <li><a href="/about">About</a></li>
    <li class="selected"><a href="/bookkeeping">Bookkeeping</a></li>
    <li><a href="/ms-office-support">MS Office Support</a></li>
    <li><a href="/office-organization">Office Organization</a></li>
    <li><a href="/virtual-services">Virtual Services</a></li>
    <li><a href="/grant-writing">Grant Writing</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>
2
  • Your code seem to work perfectly: JSFiddle. Maybe interference with your CSS? Commented Apr 28, 2014 at 16:22
  • @AndersG Yea, I used JSFiddle and it worked correctly there, just not on the live site. Commented Apr 28, 2014 at 16:30

2 Answers 2

2

You can use .children():

$("li.selected").prev().children().css("border-right", "none");

Please note that .children() only go down one level from the parent node, if you want to traverse multiple levels then you can use .find():

$("li.selected").prev().find('*').css("border-right", "none");
Sign up to request clarification or add additional context in comments.

5 Comments

This works, but is there a way to only do it on the one before it and not all of them?
I don't get what you means. Can you show a sample HTML markup and state what's your expected result?
Then your code with only .prev() should work. Here is the demo: jsfiddle.net/pLLEC
Hm, then I have no idea why it isn't working correctly. It works right for me when I updated the fiddle with what I was trying to do.
Did you wrap your code inside DOM ready handler $(function() {...}); ?
0

This worked for me to find the previous child of active <li> tag.

 $("li.selected").prev().find('a').css("background-color", "yellow");

Hope this help.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.