0

I cant figure this out I am trying to listen and when a list item changes to the class 'active' it will prepend a span element to the link inside the list item.

My html is

<ul>

  <li class="active">
    <a href="#when">When should I water my terrarium?</a>
  </li>

  <li><a href="#where">Where did the bugs come from?</a></li>

</ul>

and my jQuery is

jQuery('.cat-sidebar .widget_text li').each(function() {

if(jQuery(this).hasClass('active')) {
    jQuery('.cat-sidebar .widget_text li a').prepend('<span><i class="fas fa-angle-double-right"></i></span>');
} 

});

how would I correctly do this so the final result when the li class is active will look like this

<ul>

  <li class="active">
    <a href="#when">

      <span><i class="fas fa-angle-double-right"></i></span> 
      When should I water my terrarium?

    </a>
  </li>

  <li><a href="#where">Where did the bugs come from?</a></li>

</ul>
Ajithraj
  • 528
  • 5
  • 15
ScreamQueen
  • 206
  • 1
  • 4
  • 13
  • You are not selecting the one that you are on.... you are reselecting all the elements from the DOM – epascarello Jul 25 '19 at 13:57
  • Why are you not doing this in what is changing the class to active - if you really need to do it separately (or "listen" as you say), you may need to use a mutation observer or create your own trigger – Pete Jul 25 '19 at 14:01
  • https://stackoverflow.com/questions/1950038/jquery-fire-event-if-css-class-changed – Pete Jul 25 '19 at 14:16

1 Answers1

1

Not sure why you are looping, just do it with a selector

jQuery('.cat-sidebar .widget_text li.active a').prepend(...)

but the issue with your code is you are selecting all the elements, not working with the one you are on.

jQuery('.cat-sidebar .widget_text li')
  .each(function(){
    if(jQuery(this).hasClass('active')) {
      jQuery(this)
        .find('a')
          .prepend('<span><i class="fas fa-angle-double-right"></i></span>');
    } 
  });

Now there is no easy way to listen for a class of active being added. You can use mutation observer, but that is not going to work. Other choice is do not worry about it and just add the HTML to all the elements and show hide it with a CSS rule.

li span.myIcon {
  display: none;
}

li.active span.myIcon {
  display: inline;
}
epascarello
  • 204,599
  • 20
  • 195
  • 236