简体   繁体   中英

how i can change the class of my <li> using javascript

My project is an asp.net and it has a master page that contains a list

<ul id="navigation">
         <li id="li1" runat="server" class="selected"><a href="Events.aspx">Events</a></li>
         <li id="li2" runat="server"><a href="AddEvent.aspx">Add Event</a></li>
         <li id="li3" runat="server"><a href="MyProfile.aspx">Profile</a></li>
         <li id="li4" runat="server"><a href="Friends.aspx">Friends</a></li>
         <li id="li5" runat="server"><a href="FindFriends.aspx">Find Friends</a></li>
         <li id="li6" runat="server"><a href="Schedual.aspx">Schedual</a></li>
         <li>
             <asp:LinkButton ID="LogOutButton" runat="server" OnClick="LogOutButton_Click">Log Out</asp:LinkButton>
         </li>
</ul>

The selected class (css class) has a picture this picture tells the user on which page he is. How can I change this class using javascript or C# when I navigate?

I don't have a good experience with javascript

document.getElementById("li6").className = "whatever";

应该管用/

$("#li1").addClass("selected");

Will work.

Example

This is very simply in JavaScript/jQuery.

But if this is for navigation, meaning it needs to be updated when you display a new page, I would do this in the markup from the server.

You didn't say much about how you are serving this page. But both ASP.NET WebForms and MVC allow you to control the HTML served in a number of different ways.

You can set for all your li tags classes like this for example:

<li class="li">
 ... content of the tag
</li>

and in your javascript you can add to all elements with class "li" some other class:

$(".li").addClass("classYouWantToAdd");

and in the css file:

.li
{
  ... needed css for the class
}

here is another post that tells you how to get elements by classname

Selecting a div by classname

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