Change li element class with jQuery

I have a navigation that highlights the currently selected navigation point using the active class. When a user visits a new navigation point, I want to switch the "old" selected navigation point and switch the class of the li element of the new navigation point to "active".

I'm having problems with the jquery part, which should only switch the li class of the old element and add the class to the element with li click. This is probably a standard situation, but I do not know for this good and easy solution.

Example (until clicked):

<ul class="x-navigation">
<li class="active">
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li>
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

Result (after clicking on "Dashboard 2"):

<ul class="x-navigation">
<li>
   <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li class="active">
  <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

My attempt

$(".x-navigation li").on("click", "a", function(){
        event.preventDefault();
        //alert("test");

        ($this).parent().removeClass("active");
        ($this).addClass("active");

        //alert($this.child().href);
});

Error Description:

Uncaught ReferenceError: $this is not defined at this row: "($this).parent().removeClass("active");

Should this li element be pressed? Hope you guys can help me with such a standard problem.

+4
2

$ . - jQuery, this :

$(this).parent()

..

+5

, li "", , , "" , .

($this).addClass("active");

, , , -

$(".x-navigation li").on("click", "a", function(){

:

($this).parent().removeClass("active");

, $out of (this):

$(this).parent().removeClass("active");

, , :

$(".x-navigation li").on("click", "a", function(){
  event.preventDefault();
  $(this).parent().addClass("active").siblings().removeClass("active");
});
+2

All Articles