Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding basic DOM chaining

Tags:

javascript

dom

I'm getting started with JavaScript and the DOM, trying to purposely stay away from jQuery and the like, at least for a little while. With that in mind, tutorials generally provide an example such as this:

h = document.createElement("h1");
t = document.createTextNode("Hello.");
h.appendChild(t);
document.body.appendChild(h);

In an attempt to streamline this and avoid variables, I successfully chained the following:

document.body.appendChild(document.createElement("h1")).appendChild(document.createTextNode("Hello."));

While this works, I tried to shorten the following prepend operation:

h = document.createElement("h1");
t = document.createTextNode("Put this on top.");
h.appendChild(t);
document.body.insertBefore(h,document.body.firstChild);

with the following:

document.body.insertBefore(document.createElement("h1")).appendChild(document.createTextNode("Put this on top."),document.body.firstChild);

But this time it didn't work as desired: the text is placed at the very end of the BODY element, obtaining an append instead of a prepend.

I imagine the successful first case is just a fluke, but I can't see what's wrong with this chaining practice.

like image 318
ezequiel-garzon Avatar asked Dec 17 '12 20:12

ezequiel-garzon


1 Answers

You have parenthesis in the wrong places. Your line:

document.body.insertBefore( document.createElement("h1") )
.appendChild( document.createTextNode("Put this on top."), document.body.firstChild );

How it should be:

document.body.insertBefore(
    document.createElement("h1").appendChild(
        document.createTextNode("Put this on top.")), document.body.firstChild);

Now you understand why this is generally a bad idea to merge all in one line.

Ok, this fixed line will not give you exact behavior of your code 'with variables'. This is because .appendChild returns the child DOM element (<INPUT> in your case), not the parent (<H1> in your case). But you want so that all <H1> DOM element was added at the beginning of document. To achieve this in one line you need to use .parentNode property:

document.body.insertBefore(
    document.createElement("h1").appendChild(
        document.createTextNode("Put this on top.")).parentNode, document.body.firstChild)

Guys, please do not use such code, this is just for educational purposes)))

like image 120
SergeyS Avatar answered Nov 05 '22 00:11

SergeyS