Home > Software design >  Wrap comma separated text on page in span tags with JQuery
Wrap comma separated text on page in span tags with JQuery

Time:12-02

I have a number of comma separated values in divs on my page like this:

<div >
Within 48 hours,Annually
</div>

<div >
First 2 weeks,Annually
</div>

<div >
Annually
</div>

I am trying to wrap each value in a span tag. I have managed to do this, but it will only work on the first one, and then repeats the same values for the rest:

var frequencylabels = $('.frequency').html().split(',');
$('.frequency').empty().append(frequencylabels.map(i => `<span >${i}</span>`));
$('.frequency span').unwrap();

How can I achieve this output?

<span >Within 48 hours</span><span >Annually</span>

<span >First 2 weeks</span><span >Annually</span>

<span >Annually</span>

Here is a JSFiddle demo

CodePudding user response:

Loop your class and use split() / append() method inside loop.

Example:

$('.frequency').each(function(index, element) {
  var frequencylabels = $(this).text().split(',');
  $(this).empty().append(frequencylabels.map(i => `<span >${i}</span>`));
  $('.frequency span').unwrap();
});
.label {
  background-color: green;
  margin-right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  Within 48 hours,Annually
</div>

<div >
  First 2 weeks,Annually
</div>

<div >
  Annually
</div>

  • Related