ChrisW
ChrisW

Reputation: 5068

inserting text with createTextNode

I'm obviously missing something really obvious with how createTextNode and createElement work - I've got a very simple test to display 'Hello World' in a div, but it doesn't display:

var sp = document.createElement('div');
var tx = document.createTextNode('hello world');
sp.appendChild(tx);

What stupid thing am I doing?!

Upvotes: 0

Views: 180

Answers (5)

cocco
cocco

Reputation: 16706

TIP

Cache the document, if you plan to add alot of elements. and read about document.createDocumentFragment();;

All in one

var d=window.document;
d.body.appendChild(d.createElement('div')).appendChild(d.createTextNode('hey'))

DEMO

http://jsfiddle.net/Ba5VK/

Upvotes: 3

brbcoding
brbcoding

Reputation: 13586

var sp = document.createElement('div');
var tx = document.createTextNode('hello world');

sp.appendChild(tx);
document.querySelector('body').appendChild(sp); //  add the div to the body of the document

DEMO

Upvotes: 0

semirturgay
semirturgay

Reputation: 4201

you are missing to append sp div to body here an updated fiddle

Upvotes: 1

nzn
nzn

Reputation: 838

you forgot append sp.

document.getElementsByTagName('body')[0].appendChild(sp)

demo

Upvotes: 5

xtofl
xtofl

Reputation: 41509

You forgot to append the div to the document.

Upvotes: 2

Related Questions