jQuery find preceding non-ancestor element
How can I match an element that is preceding of the current's parent.
.parents('form')
and .closest()
does not does the job because it's not ancestor element
.prev()
doesn't works because it's not a sibling
html example:
<div class="somerandomname">
<div class="contents">
<h3 class="title">sadois</h3>
<strong>strong</strong>
<h3 class="nottitle">osdjia</h3>
<div class="sod">
<p class="paragraph">
<a class="link1" href="#">开发者_如何学Clink 1</a>
<a class="link2" href="#">link 2</a>
<a class="link3" href="#">link 1</a>
</p>
</div>
</div>
</div>
associated js:
$('p>a').hover(function(){
$(this).closest('strong').css({'background': 'red'});
}, function(){
$(this).closest('strong').css({'background': 'transparent'});
});
jsFiddle
is this what you're trying to do?
$(this).closest('.sod').siblings('strong')
http://jsfiddle.net/D3xBz/1/
you could do it that way as well:
$(this).closest('.contents').find('>strong')
assuming that the .contents div exists in your actual code
I think you have to assume you know some of the document structure. E.g:
$("strong", $(this).closest('div.container')).css({'background': 'red'});
I don't believe there's a way of assuming a traversal as it goes up the dom.
You can use closest() to match the ancestor <div>
element exposing the sod
class, then use prevAll() with the :last selector to match the preceding <strong>
element:
$("p > a").hover(function() {
$(this).closest(".sod")
.prevAll("strong:last")
.css("background", "red");
}, function() {
$(this).closest(".sod")
.prevAll("strong:last")
.css("background", "transparent");
});
Updated fiddle here.
Try
$(this).closest()
This will work its way up the parent tree and return the closest value to what you want.
精彩评论