Jquery toggles content inside an element

I am trying to swap the contents inside a button that toggles the crash navigation.

I currently have the following code:

<button class="navbar-toggle collapse in" data-toggle="collapse" id="menu-toggle-2"> <i class="fa fa-expand" aria-hidden="true"></i> Expand</button> //in js script $("#menu-toggle-2").click(function(e) { e.preventDefault(); $("#page").toggleClass("toggled-2"); }); 

I want to be able to change the contents inside,

 <i class="fa fa-compress" aria-hidden="true"></i> Collapse 

This needs to be switched, however, when you click the "Collapse" button, it returns to its original state

Doesn't seem to figure this out ...

+5
source share
3 answers

This is probably what you are looking for: https://jsfiddle.net/oaftwxt2/

 var clicked = 0; $("#menu-toggle-2").click(function(e) { e.preventDefault(); $("#page").toggleClass("toggled-2"); if(clicked == 0){ $(this).html('<i class="fa fa-compress" aria-hidden="true"></i> Collapse'); clicked = 1; }else{ $(this).html('<i class="fa fa-expand" aria-hidden="true"></i> Expand'); clicked = 0; } }); 
+1
source

You can use firstElementChild to get the <i> and then change its className to match the actual className , so it will switch between the two classes you want:

 $("#menu-toggle-2").click(function(e) { e.preventDefault(); var i = this.firstElementChild; i.className = i.className === 'fa fa-expand' ? 'fa fa-compress' : 'fa fa-expand'; $("#page").toggleClass("toggled-2"); }); 
+1
source

Here's how I do it:

 $(".navbar-toggle").click(function () { if ($(this).text().trim() == "Expand") { $(this).find("i").removeClass("fa-expand").addClass("fa-compress"); $(this).contents()[2].data = "Collapse"; } else { $(this).find("i").removeClass("fa-compress").addClass("fa-expand"); $(this).contents()[2].data = "Expand"; } }); 

Here is the JSFiddle daemon

0
source

Source: https://habr.com/ru/post/1236418/


All Articles