Sal
Sal

Reputation: 492

Selecting previous element with jquery?

Trying to select the previous h4 with jquery. Basically I have something like this:

<h4>THING I WANT 1</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

<h4>THING I WANT 2</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

<h4>THING I WANT 3</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

And in my javascript, when one of the buttons is clicked I'm trying to select only the h4 text directly before that button with:

$(this).prev("h4").text(),

This works for the first button (I'm guessing because it's immediately following the h4) but not for the subsequent buttons. prevAll is not the answer (because it selects all previous H4s) so I'm getting a bit confused.

Using the logic of $(selector).filter() my approach seems sensible to me. Would appreciate any help. I'm happy to wrap the above in a div or something if that helps.

Upvotes: 1

Views: 73

Answers (2)

Mayank Pathak
Mayank Pathak

Reputation: 3681

The easist will be to use prevAll.

Sample JSFiddle

HTML:

  <h4>THING I WANT</h4>
 <button>One</button>
 <button>Two</button>
 <button>Three</button>

Script

$('button').on('click', function()
 {
    var txt= $(this).prevAll('h4').text();
    alert(txt);
 });

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370609

prevAll is indeed the answer, but you have to select the first element in the collection, otherwise all previous h4s will be included:

$('button').on('click', function() {
  const $h4s = $(this).prevAll("h4");
  console.log($h4s[0].textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>THING I WANT 1</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

<h4>THING I WANT 2</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

<h4>THING I WANT 3</h4>
<button>One</button>
<button>Two</button>
<button>Three</button>

Upvotes: 1

Related Questions