Wrap each line text to an element using JQuery

I have this

<div class="mad-select">
<ul class="madSelect">
Hours
Days
Weeks
Months
</ul></div>

Then i want to make it like this by using JQuery

<div class="mad-select">
<ul class="madSelect">
    <li>Hours</li>
    <li>Days</li>
    <li>Weeks</li>
    <li>Months</li>
</ul></div>

How can i do this?

Answers 1

  • You can first access the text inside <ul> then split them. After that just clear anything in <ul> then add the <li>.

    $(document).ready(function(){
    
    var arr = $('.madSelect').html().split('\n');
    $('.madSelect').empty();
    
    $.each(arr, function( index, value ) {
      if ( index > 0 && index < arr.length - 1) 
        $('.madSelect').append("<li>"+arr[index]+"</li>");
    });
    
    
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="mad-select">
    <ul class="madSelect">
    Hours
    Days
    Weeks
    Months
    </ul></div>

    EDIT:

    I changed from .text() to .html(), because .html() is ~2x faster than .text()if you have only a text.


Related Articles