Skoochapp Skoochapp - 3 months ago 7
Javascript Question

Append items from array to html element - JavaScript

How to append array items to html elemnt like this :

[1,2,3]

<div class="bi bj">
<div class="bi bj">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
</div>
</div>


so it will be like this :

<div class="bi bj">
<div class="bi bj">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[1]" value="1">Test 1</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[2]" value="2">Test 2</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[3]" value="3">Test 3</label></div>
</div>
</div>


so far I know how to select div by class name

document.getElementsByClassName("bi bj")[2];

Answer

There are a bunch of great HTML template solutions. Personally, I like http://handlebarsjs.com/ but there are lots to choose from. I recommend you take a look.

That said, you can also do this mostly yourself like:

var items = [1, 2, 3];
var target = document.querySelector(".bi.bj .bi.bj");
var template = "<div><label class=\"bo bp\"><input type=\"checkbox\" name=\"addees[~id~]\" value=\"~id~\">Test ~id~</label></div>";

items.forEach(function(item) {
  target.insertAdjacentHTML("beforeend", template.replace(/~id~/g, item));
});
<div class="bi bj">
  <div class="bi bj">
    <strong>Suggestions</strong>
    <div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
  </div>
</div>

Comments