user4831663
user4831663

Reputation:

jQuery select previous element (sibling, not child)

I am trying to use jQuery to select and add a class the previous h1 element to .show_more. I have tried using prev() and closest() but neither seem to be working, any help would be appreciated.

$(document).ready(function() {
  $('.show_more').closest('h1').addClass('gummybear');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h1>Test</h1>
<p>I am a paragraph</p>
<div class="show_more">Show More</div>

Upvotes: 1

Views: 472

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

closest() searches for parents, so isn't applicable. prev() by itself won't work, as the p is between .show_more and the h1.

Instead you could use prevAll('h1').first(), like this:

$(document).ready(function() {
  $('.show_more').prevAll('h1').first().addClass('gummybear');
});
.gummybear { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Test</h1>
<p>I am a paragraph</p>
<div class="show_more">Show More</div>

The first() can be omitted if you don't mind affecting all sibling h1 elements, or if there only ever will be one of them (as there technically should be for SEO reasons).

Upvotes: 1

Related Questions