0

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';​
1
  • 2
    Thanks for all the help. This is what I got when using Jquery too much and forget about all the basis in javascript...lol +1 all. Commented Jul 5, 2012 at 17:48

5 Answers 5

4

You get nothing in your HTML, because your HTML is on the server.

You get nothing in the DOM, because you haven't added the element to the DOM.

document.body.appendChild(div);
Sign up to request clarification or add additional context in comments.

Comments

3

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/

Comments

3

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);

Comments

2

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.

Comments

1

You created the div correctly, just it hangs in nowhere. It needs to be inserted into the document, e.g. like

        var div=document.createElement('div');
        div.setAttribute('id','testttttttt');
        div.innerHTML='fjsoidfjiosdjfoi';
        document.getElementsByTagName("body")[0].appendChild(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.