user3142695
user3142695

Reputation: 17352

JQuery: Getting previous element

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

Answers (2)

Kiran
Kiran

Reputation: 20303

Use .prevAll() and :first Selector. Try this:

$(document).on('click', '.click', function() {
    $('#result').text($(this).prevAll('h3:first').text());
});

DEMO

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241188

jQuery docs - .prev():

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:

Updated Example

$('.click').prevAll('h3').first().text();

Upvotes: 2

Related Questions