Add class to previous element

72
February 25, 2018, at 12:34 PM

I just want to add class for the button after another class but it's inside of another div. Take a look at this example.

<div class="wrap">
 <button class="one">Click</button>
 <button class="two">Click</button>
</div>
<div class="bottom"></div>
.add-me{
 color:red;
}

In here, I want to add to class button one. But it needs to be applied when bottom class appears.(This is a validation message. So I can't style directly to button one.)

I tried with this way. But it only apply for wrapper div.

$('.bottom').prev('div').first().addClass('add-me');

Here is the fiddle: https://jsfiddle.net/eqhj0vm9/2/

Answer 1

You have to use $('.bottom').prev().find(':first-child').addClass('add-me'); to select the prev element's first child.

$(function() { 
  $(".activate").click(function(){ 
     $('.bottom').show(); 
     $('.bottom').prev().find(':first-child').addClass('add-me'); 
  }); 
});
.add-me { 
  color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<div class="wrap"> 
  <button class="one">Click</button> 
  <button class="two">Click</button> 
</div> 
<div class="bottom" style="display:none"> BOTTOM CLASS </div> 
 
<br /> 
<button class="activate">Activate bottom class</button>

READ ALSO
How to inject an iframe through a chrome extension without breaking client website layout

How to inject an iframe through a chrome extension without breaking client website layout

it's been weeks now and I decided to finally come forward and ask my questionI have researched many similar subjects but I can't seem to find the answer that solves my problem

56
Using jQuery to replace tags within an array?

Using jQuery to replace tags within an array?

I am new to Javascript and JQuery and I am trying to replace all my tags with upon first click, and then replace with on the second click, and so forth

83
Dynamic search form using javascript for Django project

Dynamic search form using javascript for Django project

I am trying to create a search form using jquery for Django using following tasks to do:

65
Trying to convert jQuery calls to knockout.js

Trying to convert jQuery calls to knockout.js

I have some code that I need to convert from jQuery calls to knockoutjs syntax

76