Home > Enterprise >  Loop through ol in jQuery and remove class and text
Loop through ol in jQuery and remove class and text

Time:05-02

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 >
  <li >
   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 >
  <li >
   <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); 
});

CodePudding user response:

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 >
  <li >
    General Information<span>1</span>
  </li>
  <li >
    General Information<span>2</span>
  </li>
  <li >
    General Information<span>3</span>
  </li>
</ol>

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

CodePudding user response:

With vanilla js:

document
  .querySelectorAll('ol.progress > *') // all children of <ol> with class .progress
  .foreach(elem => {
    elem.className = 'active'
    elem.innerHTML = `<a href="#">${elem.innerHTML}</a>`
  })

CodePudding user response:

I see you are using JQuery - so let's stick to this.

You are looping over the ol but you want to loop over the ol's lis. So replace

$('ol.progress').each....

by

$('ol.progress li').each....

You can remove all classes with the .removeClass() without any parameters. But as you want to preserve the active-class you have to preserve this attribute - in my version of the code (see below) I will use a variable for this.

In addition you want to replace the HTML-part and not the text-part - so your snippet would read

$('ol.progress li').each(function () {
  var is_active = false;
  is_active = $(this).hasClass('active');
  $(this).removeClass();
  if(is_active){
    $(this).addClass('active');
  }
  var newcontent = '<a href="#">'   $(this).html()   "</a>";
  $(this).html(newcontent);
});
  • Related