Xameer
Xameer

Reputation: 31237

Why is the closest not working?

We need to select the closest and immediately previous element of a particular element.

What is the way of doing it? Have tried the closest but it doesn't seems to be working.

debugger;
$(document).load(function() {
  var header = $("#btn").prevAll(".header");
  console.log(header.innerHtml);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class='header'>h1.header 1</h1>
<h1 class='header'>h1.header 2</h1>
<button id='btn'>
  button#btn
</button>
<h1 class='header'>h1.header 3</h1>
<h1 class='header'>h1.header 4</h1>

The alert should get h1.header 2 inside it.

Upvotes: 0

Views: 676

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

.header is sibling of target button and not its ancestor. You need to target previous sibling element and not parent element. use .prevAll() with :first instead:

$(document).ready(function() {
  var header = $("#btn").prevAll(".header:first");
  alert(header.text());
});

$(document).ready(function() {
      var header = $("#btn").prevAll(".header:first");
      alert(header.text());
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 class='header'>h1.header 1</h1>
    <h1 class='header'>h1.header 2</h1>
    <button id='btn'>
      button#btn
    </button>
    <h1 class='header'>h1.header 3</h1>
    <h1 class='header'>h1.header 4</h1>

Upvotes: 2

Related Questions