2

I have the following HTML generated with js:

var htmlBox = "<div><span class='name'></span><span class='age'></span></div>"

I want to display all the names from a Json object staff when I loop over it.

for(var i = 0;i <= staff.length;i++){
    $(htmlBox).find('span.name').text(staff[i]['name']); # Not sure
    $(htmlBox).find('span.age').text(staff[i]['age']); # doesn't work   

    $("#wrapper").append(htmlBox);
}

I dont' know exactly how to do it with raw js or jquery.

4
  • Do $(htmlBox).find... as-is your just working with a string. Commented Oct 22, 2018 at 22:48
  • htmlBox is just a string, unless you just didn't include you parsing it through jQuery Commented Oct 22, 2018 at 22:48
  • @LawrenceCherone see the edit with $(htmlBox), it doesn't work. Commented Oct 22, 2018 at 22:51
  • @PatrickEvans can you show me how to have it work Commented Oct 22, 2018 at 22:51

6 Answers 6

2

I suggest creating a jQuery object from your HTML string upon each iteration of your loop.
Also, since the array is zero-based, looping until i <= staff.length will go one index too far.
Instead, try i < staff.length.

var staff = [{
    'name': 'John Doe',
    'age': 100
  },
  {
    'name': 'Jane Doe',
    'age': 50
  }
];

var boxTemplate = "<div><span class='name'></span><span class='age'></span></div>";

var $wrapper = $('#wrapper');

for (var i = 0; i < staff.length; i++) {
  var $thisBox = $(boxTemplate);
  $('.name', $thisBox).text(staff[i]['name']);
  $('.age', $thisBox).text(staff[i]['age']);
  $wrapper.append($thisBox);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

In your example, jQuery is rebuilding your HTML after each update. Try the following:

var htmlBox = "<div><span class='name'></span><span class='age'></span></div>";

for(var i = 0;i <= staff.length;i++){
    var htmlJObject = $(htmlBox);
    htmlJObject.find('span.name').text(staff[i]['name']); # Not sure
    htmlJObject.find('span.age').text(staff[i]['age']); # doesn't work   

    $("#wrapper").append(htmlJObject.html());
}

Comments

2

htmlBox is just a string you need to parse it and then manipulate it.

Note

$(htmlBox).find()....

Will parse that string but it doesn't make htmlBox contain that newly created element

Instead you will need to each time you want a new element, parse it through jQuery, call find() / text(), and then append it

for(....){
    let box = $("<div><span class='name'></span><span class='age'></span></div>");
    box.find().text()
    $("#wrapper").append(box)
}

This gets you a new element each iteration that is then manipulated to what you need.

staff = [
  {name:"test",age:33},
  {name:"test2",age:18},
  {name:"test3",age:56},
]

for (var i = 0; i < staff.length; i++) {
  let box = $("<div><span class='name'></span> <span class='age'></span></div>");
  box.find('span.name').text(staff[i]['name']);
  box.find('span.age').text(staff[i]['age']);

  $("#wrapper").append(box);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>

Comments

2

You are not storing the parsed html of your string, try this:

for(var i = 0; i < staff.length; i++) {
    var htmlBox = $("<div><span class='name'></span><span class='age'></span></div>");

    htmlBox.find('span.name').text(staff[i]['name']); // Not sure
    htmlBox.find('span.age').text(staff[i]['age']); // doesn't work   

    $("#wrapper").append(htmlBox);
}

Also watch out I changed the condition of your for loop, it was checking for <= and should be <, because in JS array indexes start from 0.

Also also comments in JS are with // for single line or /* and */ for multi line.


Here you have a working code snippet (with some extra stuff to make it actually work)

var staff = [
  {name: 'Eu Chi', age: '??'},
  {name: 'Alvaro Castro', age: '29'}
];
for(var i = 0; i < staff.length; i++) {
  var htmlBox = $("<div><span class='name'></span><span class='age'></span></div>");

  htmlBox.find('span.name').text(staff[i]['name']); // Not sure
  htmlBox.find('span.age').text(staff[i]['age']); // doesn't work   

  $("#wrapper").append(htmlBox);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>

1 Comment

Thank you very much! it helps a lot
1

Use append with template literal to substitute with the values from object.

const staff = [{name: 'one', age: 25}, {name: 'two', age: 30}];
const htmlBox = document.createElement('div');

staff.forEach((ele) => {
  htmlBox.append(`<span class='name'>${ele.name}</span>
    <span class='age'>${ele.age}</span>`);    
});

document.getElementById('root').append(htmlBox);
<div id="root"></div>

Comments

0

Iterate your JSON using .each() and append each iteration into a container.

.each()

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

var data = [{
    'name': 'Micheal',
  },
  {
    'name': 'Jordan',
  }
];

$.each(data, function(i,v) {
  $('#content').append("<span class='name'>" + v.name + "</span>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.