简体   繁体   中英

Writing HTML for a string of values using javascript and jquery?

I want to have my page's html to appear as:

<div class='container'>
  <div class='domain-list0'>Hello</div>
  <div class='domain-list1'>World</div>
</div>

Here is my html and js: Pen from Codepen.io

Instead of creating the first "domain-list" and then creating another one for the next, it is just overwriting the previous "domain-list". This is why it shows the last string value. Anyone know how to fix this?

Thanks!

You are using .html() which removes the existing content, and replaces it with the new content. You need to use append so that the new content is added after the last child.

var myStringArray = ["Hello", "World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    var $el = $("<div  />", {
        'class': 'domain-list' + i,
        html: "<p>" + myStringArray[i] + "</p>"
    }).appendTo("div.container");
    // $el refer to the newl added element
}

Demo: Fiddle

  • use .appendTo() so that it will return the newly created element which can be used for further processing
for (var i = 0; i < arrayLength; i++) {
  $("div.container").html("<div class='domain-list'></div>");
  $(".domain-list:nth-child("+i+")").html("<p>"+myStringArray[i]+"</p>");
  //Do something
}

Try to use appendTo in jquery

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
  $("<div class='domain-list"+i+"'></div>").html("<p>"+myStringArray[i]+"</p>").appendTo("div.container");
  //Do something
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM