I have the below jquery where i have created the dynamic html structure
var data = [{ "name": "Afghanistan", "code": "A" }, { "name": "AndorrA", "code": "A" }, { "name": "Bouvet Island", "code": "B" }, { "name": "Cook Islands", "code": "C" }]; $.each(data, function(key, val) { if (!$("#aZContent ul." + val.code).is("*")) { $("<ul />", { "class": val.code, "html": "<li>" + val.name + "</li>" }) .appendTo("#aZContent ol") .before('<b class=' + val.code + '>' + val.code + '</a></b>'); } else { $("b." + val.code).each(function() { if (this.textContent === val.code) { $(this).next("ul").append("<li>" + val.name + "</li>"); } }) } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="aZContent"> <ol></ol> </div>
How to wrap the "b" and "ul" element with "li"
<li>
<b></b>
<ul>
<li></li>
</ul>
</li>
Try utilizing $.each()
, .appendTo()
, .append()
; setting ol li
, b
class
to code
property of data
.
$(function() { var data = [{ "name": "Afghanistan", "code": "A" }, { "name": "Bouvet Island", "code": "B" }, { "name": "Cook Islands", "code": "C" }]; $.each(data, function(key, val) { if (!$("#aZContent ul." + val.code).is("*")) { // append `<li>` to `ol` $("<li />", { // set `class` to `val.code` "class": val.code, // set `li` `html` to `b` , `ul` , `li` "html": "<b class=" + val.code + ">" + val.code + "</a></b>" + "<ul><li>" + val.name + "</li></ul>" }) .appendTo("#aZContent ol") } else { $("b." + val.code).each(function() { if (this.textContent === val.code) { // append `li` to `ul` $(this).next("ul").append("<li>" + val.name + "</li>"); } }) }; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="aZContent"> <ol></ol> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.