I thought the following script will create div element but I got nothing output in my html. Could anyone help me out? Thanks a lot.
var div=document.createElement('div');
div.setAttribute('id','testttttttt');
div.innerHTML='fjsoidfjiosdjfoi';
I thought the following script will create div element but I got nothing output in my html. Could anyone help me out? Thanks a lot.
var div=document.createElement('div');
div.setAttribute('id','testttttttt');
div.innerHTML='fjsoidfjiosdjfoi';
You have to use the appendChild method in the end:
var div=document.createElement('div');
div.setAttribute('id','testttttttt');
div.innerHTML='fjsoidfjiosdjfoi';
document.body.appendChild(div);
Otherwise, the created element will exist, but won't appear in your page.
Also, you have to be sure that document.body exists, otherwise, it will throw an error (if this script is going to be executed when loaded, put it inside an onload event).
PS: You can also append to any other DOM elements:
document.getElementById('myDivHolder').appendChild(div);
JSFiddle example: http://jsfiddle.net/AkXTr/
In addition to creating the element, you must insert it into the DOM. You can use the appendChild() method to add it to the end of a given parent element:
var div=document.createElement('div');
div.setAttribute('id','testttttttt');
div.innerHTML='fjsoidfjiosdjfoi';
// Now, append it
document.getElementById('someOtherElement').appendChild(div);
You'll actually need to append it to something; I'm guessing document.body will do.
var div = document.createElement('div');
div.id = 'testttttttt';
div.innerHTML = 'fjsoidfjiosdjfoi';
document.body.appendChild(div);
Make sure you do this when document.body actually exists, though, i.e. in a load event or inside the body element itself.