9780
![How to add a class to previous div [duplicate]](https://www.xszz.org/skin/wt/rpic/t25.jpg)
Question:
This question already has an answer here:
<ul><li> <a href="/questions/11134794/prev-and-next-usage-clarification-jquery" dir="ltr" rel="nofollow">prev(); and next(); usage clarification Jquery</a> <span class="question-originals-answer-count"> 4 answers </span> </li> </ul>I need to add class to the first div before the "current" class.
<div></div>
<div></div>
<div class="current">Current</div>
<div ></div>
<div></div>
I just found out how to do it for the next div but still looking for solution to get the class before it.
$(document).ready(function(){
$(".current + div").addClass("prv");
});
<a href="https://fiddle.jshell.net/0d7csqgb/2/" rel="nofollow">https://fiddle.jshell.net/0d7csqgb/2/</a>
Do anyone know how I can do it?
//EDIT
Here's working solution if somebody need: <a href="https://fiddle.jshell.net/df9ef0hf/6/" rel="nofollow">https://fiddle.jshell.net/df9ef0hf/6/</a>
Answer1:You can use prev
function..
$(document).ready(function() {
$(".current").prev().addClass("prv");
});
<pre class="snippet-code-css lang-css prettyprint-override">.prv{
background-color: red;
}
<pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>one</div>
<div>two</div>
<div class="current">Current</div>
<div>tree</div>
<div>four</div>
Answer2:<pre class="snippet-code-js lang-js prettyprint-override">
$(document).ready(function(){
$(".current").prev().addClass("prv");
$(".current").next().addClass("next");
});
<pre class="snippet-code-css lang-css prettyprint-override">.prv{color:red;}
.next{color:green;}
<pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>...</div>
<div>prv</div>
<div class="current">Current</div>
<div >next</div>
<div>...</div>
Answer3:Try the following:
<pre class="snippet-code-js lang-js prettyprint-override">$(document).ready(function(){
$('.current').prev('div').addClass('prv');
});
<pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div class="current">Current</div>
<div ></div>
<div></div>