Loop through ol in jQuery and remove class and text

I have to loop through a ol and then get each of the li and then remove the text and add "<a" element to it.
Following is the html that is rendered:

<ol class="progress">
  <li class="list-group-item text-muted list-group-item-success active">
   General Information<span>1</span>
  </li>
</ol>

I want to remove all the classes except "active" and then wrap the text with General Information
Like below

<ol class="progress">
  <li class="active">
   <a href="#">General Information<span>&nbsp;1</span></a>
  </li>
</ol>

I have tried to loop through the Ol using the script below but it seems to not find anything

$('ol.progress').each(function (i, li) {
 var listItem = li;
 var lm = $(li).text();
 console.log(lm); 
});

>Solution :

With jquery, as you can see, I check if the element has a class, then I remove all the classes and add active if it had it.

$('ol.progress li').each(function(i, li) {
  var listItem = li;
  if ($(li).hasClass('active')) {
    $(li).removeAttr('class');
    $(li).addClass('active');
  } else {
    $(li).removeAttr('class');
  }
});
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="progress">
  <li class="list-group-item text-muted list-group-item-success active">
    General Information<span>1</span>
  </li>
  <li class="list-group-item text-muted list-group-item-success">
    General Information<span>2</span>
  </li>
  <li class="list-group-item text-muted list-group-item-success">
    General Information<span>3</span>
  </li>
</ol>

In your code you forgot li into selector so $('ol.progress li') instead of $('ol.progress')

Leave a Reply