Using Javascript to add elements to a page with class or ID

By Eric Downing. Filed in html, Javascript  |  
TOP del.icio.us digg

There are times you might want to dynamically generate elements on a page and add classes to style them. You can create elements with ids and/or classes with plain Javascript with the following commands:

var newElement = document.createElement(“div”);
//to add a class:
newElement.setAttribute(“class”, “card”);
//to add an id
newElement.setAttribute(“id”, “id_name”);
//to add it to the body:
document.body.appendChild(newElement);
// or to add it to some element:
document.getElementById(“card-box”).appendChild(newElement);

You could also create the string for an element and attach it to the content of a div.

var newElement = '<div id="id_name" class="card">Some Content</div>';
 // This will replace the contents with your new element. 
document.body.innerHTML = newElement;

Leave a Reply