My html
<div >
<div >
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 >
<div >
<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.
CodePudding user response:
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.
CodePudding user response:
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)
}
});