Adnan Jamil Adnan Jamil - 3 months ago 9
HTML Question

How to wrap HTML text in each new line with <li> tag?

I have this code:

<aside id="jmfe_widget-2" class="widget widget-job_listing widget_jmfe_widget">

<h2 class="widget-title widget-title-job_listing %s">Amenities</h2>

Air conditioning<br>
Free parking<br>
Access to bathrooms<br>
Loading dock<br>
Elevator<br>

</aside>


I want to wrap these points as list items, like this:

<aside id="jmfe_widget-2" class="widget widget-job_listing widget_jmfe_widget">

<h2 class="widget-title widget-title-job_listing %s">Amenities</h2>

<li>Air conditioning</li><br>
<li>Free parking</li><br>
<li>Access to bathrooms</li><br>
<li>Loading dock</li><br>
<li>Elevator</li><br>

</aside>


Anyway that's possbile with jQeury?

Answer

First, you need to wrap each item within a div and give it a class, like so

<aside id="jmfe_widget-2" class="widget widget-job_listing widget_jmfe_widget">

    <h2 class="widget-title widget-title-job_listing %s">Amenities</h2>

    <div class="item">Air conditioning</div>
    <div class="item">Free parking</div>
    <div class="item">Access to bathrooms</div>
    <div class="item">Loading dock</div>

</aside>

Then, do this in jQuery

$('.item').each(function(){
   $(this).wrap('<li></li>');       
});

DEMO https://jsfiddle.net/tu5u0an3/2/

If you can't add any HTML, then try this

$( "#jmfe_widget-2" )
  .contents()
    .filter(function() {
      return this.nodeType === 3;
    })
  .wrap( "<li></li>" )
  .end()
.filter( "br" )
.remove();

This will look inside your aside element, get the contents, remove <br> tags and replace them with <li></li>

DEMO https://jsfiddle.net/tu5u0an3/5/

Comments