views:

26

answers:

2

Hi guys lets say I have the following html:

<div class="owner">
  <div>
    <a href="javascript:void(0)" onclick="">click</a>
  </div>
</div>
<div class="owner">
  <div>
    <a href="javascript:void(0)" onclick="">click</a>
  </div>
</div>

I want to put code in the onclick handler so it results in selecting the element of class 'owner' which encloses it - so I don't have to refer to the parent element by typing in this.parentNode.parentNode etc

I'd appreciate if theres a way to do it using selectors from both prototype and jquery.

+1  A: 

Why not use this.parentNode.parentNode? If the structure is fixed, this will be faster and more efficient.

If the structure is not fixed, a jQuery way would be something like:

$(this).parentsUntil (".owner").filter (".owner");
Brock Adams
This is a very simple example - at times the element is nested really deep inside and is alot of parentNodes away from the one I wish to target and most of the time I end up having to redesign the html a bit so I want to avoid having to redo all the javascript in such cases as its very dependant upon the actual positioning of the element itself.
Ali
+1  A: 

$().parents(<selector>) is your friend

$(a).click(function() {
   $(this).parents(".owner").css("background-color", "yellow");
})

example

john_doe
Cool - is there a similar function in prototype?
Ali
in prototype 'up' seems to be the equivalent to jquerys parents()http://www.prototypejs.org/api/element/up
john_doe
Thanks man :D this just saved me loads of coding time.
Ali