简体   繁体   中英

Move selected attribute in html list using jquery

If I have a list like this, how do I make it so that if I click on one of the unselected item links that it moves the class="active" to that list item instead and removes it from the old one?

Before:

<ul>
<li class="active"><a href="#">item 1</a></li>
<li><a href="#">item 2</a></li>
<li><a href="#">item 3</a></li>
</ul>

After clicking on the third link:

<ul>
<li><a href="#">item 1</a></li>
<li><a href="#">item 2</a></li>
<li class="active"><a href="#">item 3</a></li>
</ul>

You should use classes. So :

$('li').click(function() {
    $('li').removeClass('active');
    $(this).addClass('active');
});

also see this post for further support. It's close li menu needs class of "selected"

Jquery: https://api.jquery.com/addclass/

It is rather simple. When a <li> is clicked then add the class to the clicked element and remove it from the one that currently has it.

$("ul").on("click", "li", function () {
    $(this).addClass("active").siblings(".active").removeClass("active");
});

In this code when a <li> is clicked that element is given the active class and then we find the sibling element that currently has the class and remove the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM