Reputation: 17352
I want to get the first previous h3-tag of a set of elements.
Example:
<h3>Any title</h3>
<div>First></div>
<div>Second></div>
<div>Third></div>
<h3>Get result</h3>
<div>First></div>
<div>Second></div>
<div class="click">Third></div>
$('.click')
should give me the result <h3>Get result</h3>
. But it is not the direct previos element, so my attempt doesn't work:
$('.click').prev('h3').text();
JSFiddle: http://jsfiddle.net/36p60n5u/
Upvotes: 2
Views: 54
Reputation: 20303
Use .prevAll()
and :first Selector
. Try this:
$(document).on('click', '.click', function() {
$('#result').text($(this).prevAll('h3:first').text());
});
Upvotes: 1
Reputation: 241188
Description: Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
As stated above, .prev()
will get the immediately preceding sibling element. Therefore you should use .prevAll()
in combination with .first()
or :first
in order to get the first match:
$('.click').prevAll('h3').first().text();
Upvotes: 2