Dragan Marjanovic
Dragan Marjanovic

Reputation: 1287

Dynamically generating lists without document.write?

I'm using JavaScript to create a list of links from a text source. Using document.write(), resets/creates a new page which is not desirable. I do not know the amount of items in the list, so precomposing a list and using innerHTML to set values doesn't seem 'do-able' ? How would one go about generating dynamic lists in JS?

Upvotes: 0

Views: 78

Answers (2)

Robert Onodi
Robert Onodi

Reputation: 120

As Matti Mehtonen stated you can use document.createElement(), in order to create dynamically elements. One note on this is that instead of appending the newly created elements directly into a DOMnode, you should instead create a document fragment and append the elements to it, afterwards you append the fragment to the DOMnode. This way the process will be faster.

var items = ['cars', 'toys', 'food', 'apparel'];

function render(elementId, list) {
  //getting the list holder by id
  var el = document.getElementById(elementId);

  //creating a new document fragment
  var frag = new DocumentFragment();

  //iterate over the list and create a new node for
  //each list item and append it to the fragment
  for (var i = 0, l = list.lenght; i < l; i++) {
    var item = document.createElement('span');
    frag.appendChild(item.innerHTML = list[i]);
  }

  //finally append the fragment to the list holder
  el.appendChild(frag);
}

//rendering
render("my-list-holder", list);

Upvotes: 1

Matti Mehtonen
Matti Mehtonen

Reputation: 1705

You can create elements dynamically by using document.createElement. It could work for example like this:

var container = document.getElementById('my-list'),
    items = [],
    addItem;

addItem = function (text) {
    var elm = document.createElement('li');

    elm.innerHTML = text;
    container.appendChild(elm);
    items.push(elm);
};

// generating random list
var i = 0,
    j = Math.floor(Math.random() * 50);

for (i; i < j; i++) {
    addItem('list item ' + i);
}

Upvotes: 1

Related Questions