skip to Main Content

My html

<div class="note">
  <div class="fielditem">
   test one<br>
   test two
  </div>
</div>

I am using jquery to wrap each line with li which is working well.

jQuery(document).ready(function($) {
  var listHTML = $('.note .fielditem').html();
  if (listHTML !== undefined && listHTML !== null) {
  var listItems = listHTML.split('<br>');
  $('.note .fielditem').html('');
  $.each(listItems, function(i, v) {
    var item = '<li>' + v + '</li>';
    $('.note .fielditem').append(item);
  });
 }
});

Now i want to insert ul tag around all the li items, like this

<div class="note">
  <div class="fielditem">
   <ul>
    <li>test one</li>
    <li>test two</li>
    </ul>
  </div>
</div>

Tried searching but couldn’t come up with relevant answers. Thanks for any help.

2

Answers


  1. Try this.

    jQuery(document).ready(function($) {
      var listHTML = $('.note .fielditem').html();
      if (listHTML !== undefined && listHTML !== null) {
        var listItems = listHTML.split('<br>');
        $('.note .fielditem').html('');
        $.each(listItems, function(i, v) {
          var item = '<li>' + v + '</li>';
          $('.note .fielditem').append(item);
        });
        $('.note .fielditem li').wrapAll('<ul>');
      }
    });
    

    This will select all the <li> elements inside the .fielditem div, and wrap them all in a <ul> tag using the .wrapAll() method.

    Login or Signup to reply.
  2. Try this..

    Ans1:

    jQuery(document).ready(function ($) {
       var listHTML = $(".note .fielditem").html();
       var elementList = $(".note .fielditem");
       if (listHTML !== undefined && listHTML !== null) {
         var listItems = listHTML.split("<br>");
         $(".note .fielditem").html("");
    
         let my_ul = $("<ul>");
         $.each(listItems, function (i, v) {
           my_ul.append($("<li>").append(v));
         });
         elementList.append(my_ul);
        }
    });
    

    Ans2:

    jQuery(document).ready(function ($) {
      var listHTML = $(".note .fielditem").html();
      var elementList = $(".note .fielditem");
      if (listHTML !== undefined && listHTML !== null) {
        var listItems = listHTML.split("<br>");
        $(".note .fielditem").html("");
    
        let my_ul_list = "<ul>";
         $.each(listItems, function (i, v) {
         my_ul_list += "<li>"+v+"</li>"
         });
         my_ul_list += "</ul>"
         elementList.html(my_ul_list) 
       }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search