Jquery: is it possible to select an element only if it is followed by an element with a specific class?

problem:

I want to use jquery to add a 'warm' class to any li adjacent to li.hot

<ul>
    <li></li> * ? (unknown amount of li's)
    <li></li>
    <li class="hot"></li>
    <li></li>
    <li></li> * ? (unknown amount of li's)
</ul>

      

+2


a source to share


2 answers


If by "adjacent", you mean the previous and next items, then you can use . prev () and . next () .



var liHot = $("li.hot");
liHot.prev("li").addClass("warm");
liHot.next("li").addClass("warm");

      

+5


a source


$('li.hot').prev().addClass('warm');
$('li.hot').next().addClass('warm');

      



I know this is basic, but you get the idea.

0


a source







All Articles