开发者

How do I select the first instance of an element of a certain class enclosinga DOM element

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开发者_StackOverflow社区.parentNode.parentNode etc

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


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

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

example


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜