views:

32

answers:

3

Hi there..

Having a few issues with JQuery traversal and looking for some asssistance..

If i have the following html

<div id="1">
This is a div
</div>
<div id="2">
<a href="link">This is div 2</a>
</div>

What I would like to do, is when I click on the link in div 2, is add a class to div1 using dom traversal, and not just directly refering to div 1s id....

Many thanks

+4  A: 

http://api.jquery.com/prev/

This should do it:

$('a').click(function() {
  $(this).parent().prev().addClass('previous');
});
Cryo
Either use `prevAll('div')` or `prev()`. Using both means if any other node comes between them, nothing is selected. Not sure if that is what you want. Either way +1!
Doug Neiner
Thanks for pointing that out, I've updated my answer.
Cryo
Worked like a beauty! Thanks a lot
namtax
A: 
$("#2 a").click(function(e) {
    e.preventDefault();
    $(this).parent().prev().addClass("myNewClass");
});

btw: ids have to start with a letter not a number

harpax
A: 

Check out .prev()

Oscar Kilhed