0
var family = {
    dad: 'Father',
    mom: 'Mother',
    son: 'Boy',
    daughter: 'Girl'
}

for ( var person in family ) {
    console.log('<li>' + 'the ' + person + ' is a ' + family[person] + '</li>')
}

I want to know what the best way to insert this into the DOM instead of logging it to the console. I want to use just JavaScript

David G
  • 94,763
  • 41
  • 167
  • 253
pixel 67
  • 1,530
  • 18
  • 22

2 Answers2

1

Depends on what is already in the HTML. If you're simply adding exactly what you have, it wouldn't be a bad idea to just use:

var all_family = "";
for (var person in family) {
    all_family += "<li>the " + person + " is a " + family[person] + "</li>";
}
document.getElementById("main_ul").innerHTML = all_family;

where "main_ul" is:

<ul id="main_ul"></ul>

Another option is:

var ul = document.getElementById("main_ul");
for (var person in family) {
    var li = document.createElement("li");
    li.innerHTML = "the " + person + " is a " + family[person];
    main_ul.appendChild(li);
}

Something you might look at to help decide which to use: "innerHTML += ..." vs "appendChild(txtNode)"

Community
  • 1
  • 1
Ian
  • 50,146
  • 13
  • 101
  • 111
  • I was thinking of doing something like David was trying to do below, but this works too. It is better practice to create the nodes like the example below correct? – pixel 67 Oct 02 '12 at 00:54
  • @pixel67 I really don't know which is better. When dealing with more complicated things, like deeper nested elements and event handling, it's probably preferred to use `createElement` and manipulate things like that. But if you're doing something simple like this, I really don't know if it makes a difference. You can take a look at http://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode – Ian Oct 02 '12 at 00:57
0

Native, cross-browser DOM methods are the safest.

var list = document.createElement('li');

for (var person in family)
   list.appendChild(
       document.createTextNode('the person is a ' + family[person]) );

document.body.appendChild( list );
David G
  • 94,763
  • 41
  • 167
  • 253