lorenc55 lorenc55 - 2 months ago 12
jQuery Question

How to add a class to the next element of current element array in jquery?

I would like to know how to do such thing.

e.g. I have something like this:

<ul>
<li><a href="1.html">first item</a></li>
<li><a href="2.html">second item</a></li>
<li><a href="3.html">third item</a></li>
<li><a href="4.html">fourth item</a></li>
</ul>


I need to addClass to a hover a element, this is easy I do it like this:

$("li a").hover(
function () {
$(this).addClass("show");
},
function () {
$(this).removeClass("show");
}
);


However, I need to addClass to every next li element also.

So, when e.g. first li a eleemnt is hovering the class show2 will be added to li a of the second li a element.

How to do this?

Answer

Try this

$("li a").hover(
              function () {
                $(this).addClass("show").parent().next().addClass("show2");               


              },
              function () {
                $(this).removeClass("show").parent().next().removeClass("show2");

              }
            );