Skip to content Skip to sidebar Skip to footer

How To Add A Class To Previous Div

I need to add class to the first div before the 'current' class.
Current

Solution 1:

$(document).ready(function(){
    $(".current").prev().addClass("prv");
    $(".current").next().addClass("next");
});
.prv{color:red;}
.next{color:green;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>...</div><div>prv</div><divclass="current">Current</div><div >next</div><div>...</div>

Solution 2:

You can use prev function..

$(document).ready(function() {
  $(".current").prev().addClass("prv");
});
.prv{
background-color: red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>one</div><div>two</div><divclass="current">Current</div><div>tree</div><div>four</div>

Solution 3:

Try the following:

$(document).ready(function(){
    $('.current').prev('div').addClass('prv');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div></div><div></div><divclass="current">Current</div><div ></div><div></div>

Post a Comment for "How To Add A Class To Previous Div"