I have two unordered lists inside a div with a known class. I need to change the list items in the first list to spans with the class "time". Next I would like to change the second list items to spans with the class "frequency". Finally I would like to remove the <ul>
tags leaving only the spans behind in the div. Just like:
<div id="training-labels">
<ul>
<li>30 mins</li>
</ul>
<ul>
<li>Annually</li>
<li>First 2 weeks</li>
</ul>
</div>
to this
<span class="time">30 mins</span>
<span class="frequency">Annually</span>
<span class="frequency">First 2 weeks</span>
I have managed to change the contents of each list into spans:
$('#training-labels ul:nth-of-type(1) li').wrapInner('<span class="time" />').contents();
$('#training-labels ul:nth-of-type(2) li').wrapInner('<span class="frequency" />').contents();
But have not been successful stripping out the ul and li tags, leaving only the spans behind.
Is this the best approach or is there a better way to achieve this with JQuery?
I have set up a Fiddle here
$('#training-labels ul:nth-of-type(1) li').wrapInner('<span class="time" />').contents();
$('#training-labels ul:nth-of-type(2) li').wrapInner('<span class="frequency" />').contents();
.time {
color: green;
}
.frequency {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="training-labels">
<ul>
<li>30 mins</li>
</ul>
<ul>
<li>Annually</li>
<li>First 2 weeks</li>
</ul>
</div>
4
Answers
You can do following:
JQuery
wrap()
method:JQuery
unwrap()
method:Note: Since no class is attached to the parent div (with the id
training-labels
), both the spans are in the same row.If we can be sure all ul1 has times and all ul2 has frequencies
Otherwise
My approach
This is not dissimilar from the
unwrap
solution except that it is not so tightly tied to the tag structure. Theclone
part isn’t strictly required but it means that there is actually only one update to the DOM which happens after the entire replacement has been generated.While you’ve already accepted an answer, I wanted to take the time to show a non-JavaScript (or jQuery) CSS-only approach that may work for you, depending on the desired end-result:
JS Fiddle demo.
References:
CSS:
::after
.::before
.block-size
.border
.clamp()
.content
.display
.font-family
.font-size
.gap
.grid-column
.grid-template-columns
.inline-size
.:is()
.:last-child
.list-style-type
.margin-block
.margin-inline
.:not()
.:only-child
.padding
.repeat()
.var()
.:where()
.