5

I'm trying to figure out what is the differences between this two:

// first one
var h1 = document.createElement('h1');
var t = document.createTextNode('hey');
h1.appendChild(t);
document.body.appendChild(h1);

// second one
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));

The first (Document.createElement()) works perfectly, but the second (Document.createTextNode()) does not.

3
  • 1
    Because appendChild returns the appended node, so you're trying to append a text node to body... Commented Dec 13, 2016 at 14:14
  • the result of document.createElement('h1').appendChild(document.createTextNode('hey') is the text node ... therefore you are appending the text node to the body Commented Dec 13, 2016 at 14:14
  • Document.createElement + Document.createTextNode one-liner? Commented Dec 13, 2016 at 14:19

2 Answers 2

3

The return value of appendChild is the appended child.

So if we add variables to:

document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));

it gets broken down into:

var text = document.createTextNode('hey');
var h1 = document.createElement('h1');
h1.appendChild(text);
document.body.appendChild(text);

Appending the text to the body removes the text from the h1.

The h1 is discarded because it is never appended anywhere.

Sign up to request clarification or add additional context in comments.

4 Comments

Now, let's assume i'm starting with document.body.appendChild(document.createElement('h1')); and this h1 tag doesn't have id, so how can I add to this tag some text?
You'd have to search the document for it. Use a variable. Don't try to stuff multiple operations into a single statement.
OK. Iv'e tried to code it in one line because I need to build an entire html page in JS. :)
h1.innerText does the same thing as working with text nodes, and is much easier.
0

I find a way to do it: (just add .parentNode at the end)

document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')).parentNode);

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.