Alejandro
Alejandro

Reputation: 427

How to combine this two javascript lines in just one line

am trying to figure out a way of combining the below statements

document.getElementById( 'div1' ).appendChild( document.createElement( 'div' ) ).id="div2";
document.getElementById( 'div2' ).appendChild( document.createTextNode( 'More about me' ) );

Upvotes: 3

Views: 1578

Answers (2)

Purag
Purag

Reputation: 17061

Disclaimer: This isn't a good thing to do at all, and I will explain why in a moment.

document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + "<div id='div2'>More about me</div>";

What this does is ensure that the new div gets appended and doesn't simply replace the content of the existing div.

Now obviously, this is pretty ugly code.

The reason this is bad is because what we're doing is inserting what we seem to think or are led to believe are actual elements. This is false—we're inserting a string which is translated into an element later on. This is just purely inconvenient for us.

The use of DOM scripting (which is what you had before—actually creating an element and appending it) creates elements as actual HTML objects. The point is that it's just much more pure input (and, in most cases, executes quicker than innerHTML).

Using innerHTML is becoming much more common now, which I like to lead myself to doubt simply because I'm such a Javascript nerd and, from what I've learned (on this site, in fact), DOM scripting is much better in many, many ways.

Secondly, DOM scripting can be so much neater and easier to maintain than innerHTML. You can probably tell that the code I've given you above is not convenient at all. ;)

Upvotes: 0

Francis Avila
Francis Avila

Reputation: 31621

appendChild() returns a reference to the node you just added, so the second getElementById is not necessary:

document.getElementById('div1').appendChild(document.createElement('div'))
.appendChild(document.createTextNode('More about me'))
.parentNode.id="div2"; // only if you need the second div to have id="div2" for some other reason.

Upvotes: 3

Related Questions