1

Every same child type should wrap in div. The problem is I am getting single array which contains all the children. So I am running loop over it and tried to create new div and close it when children type changed but it is not well written.

fiddle

var items = [{
  "type": "child1",
  "name": "1 "
}, {
  "type": "child1",
  "name": "1 "
}, {
  "type": "child1",
  "name": "1 "
}, {
  "type": "child2",
  "name": "2 "
}, {
  "type": "child2",
  "name": "2"
}, {
  "type": "child3",
  "name": "3 "
}, {
  "type": "child3",
  "name": "3 "
}, {
  "type": "child3",
  "name": "3"
}]
var child = "";
var html = ''

items.forEach(function(item) {
  if (child !== item.type) {
    html += '<div>'
  }
  html += '<div>' + item.name + ' </div>';
  if (child !== item.type && child) {
    html += '</div>'
  }
  child = item.type;

})

document.getElementById('html').innerHTML = html;
div { border:1px solid black }
<div id="html"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jitender
  • 7,593
  • 30
  • 104
  • 210

3 Answers3

1

what you should do, is when you check whether child is not the same with item.type, you should add a closing </div> and a new open <div>

items.forEach(function(item) {
 if(child != item.type){
    html += '</div>';
    html += '<div>';
 }
 html += '<div>' + item.name + ' </div>';
 child = item.type;
})

demo : https://jsfiddle.net/0sz9xpxq/2/

Mark
  • 2,041
  • 2
  • 18
  • 35
1

You can try this, https://jsfiddle.net/trupti11/0sz9xpxq/4/

var html = '<div>';  
items.forEach(function(item) {
      if (child != item.type && child) {
        html += '</div><div>'+ item.name;
      }
      else
      {
      html += item.name;
      }
      child = item.type;

    })
    html += '</div>';
pravid
  • 719
  • 9
  • 27
0

Instead of messy text manipulation, you can use document.createElement to do it a lot cleaner. There's a great answer to this SO question that talks about the benefits of using createElement vs adding a string to innerHTML

var child = "";
var html = document.getElementById('html');
var node;

items.forEach(function(item) {
  if (child !== item.type) {
    if (node) {
        html.appendChild(node);
    }
    node = document.createElement('div');
  }
    var newElem = document.createElement('div');
    newElem.innerHTML = item.name;
    node.appendChild(newElem);

  child = item.type;

});

html.appendChild(node);

Fiddle

Daniel Bernsons
  • 650
  • 7
  • 20