JavaScript - append() method

revision:


Category : document

The Document.append() method inserts a set of Node objects or string objects after the last child of the document. String objects are inserted as equivalent Text nodes.

This method appends a child to a document. To append to an arbitrary element in the tree, "Element.append()" method can be used.

Syntax :

        append(param1)
        append(param1, param2)
        append(param1, param2, /* … ,*/ paramN)

Parameters

param1, …, paramN : a set of Node or string objects to insert.

The append() method will insert DOMString objects as "text" nodes. The append() method has no return value, what means that the method implicitly returns "undefined".

Examples:

            let html = document.createElement("html");
            document.append(html);
            // HierarchyRequestError: The operation would yield an incorrect node tree.
        
            let doc = new Document();
            let html = document.createElement("html");
            doc.append(html);
            doc.children; // HTMLCollection [<html>]
        

Category: element

The Element.append() method inserts a set of Node objects or string objects after the last child of the Element. String objects are inserted as equivalent Text nodes.

Differences from Node.appendChild():

Element.append() allows you to also append string objects, whereas Node.appendChild() only accepts Node objects.
Element.append() has no return value, whereas Node.appendChild() returns the appended Node object.
Element.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.

Syntax :

            append(param1)
            append(param1, param2)
            append(param1, param2, /* … ,*/ paramN)

Parameters

param1, …, paramN : a set of Node or string objects to insert.

The append() method will insert DOMString objects as "text" nodes. The append() method has no return value, what means that the method implicitly returns "undefined".

Examples:

            let div = document.createElement("div");
            let p = document.createElement("p");
            div.append(p);
            console.log(div.childNodes); // NodeList [ <p> ]
        
            let div = document.createElement("div");
            let p = document.createElement("p");
            div.append("Some text", p);
            console.log(div.childNodes); // NodeList [ #text "Some text", <p> ]
        

Practical examples

example: using the append() method to append an element:
  • JavaScript
code:
                    <div class="spec">
                        <ul id="app" style="margin-left:5vw;">
                            <li>JavaScript</li>
                        </ul>
                    </div>
                    <script>
                        let app = document.querySelector('#app');
                        let langs = ['TypeScript','HTML','CSS', 'jQuery'];
                        let nodes = langs.map(lang => {
                            let li = document.createElement('li');
                            li.textContent = lang;
                            return li;
                        });
                        app.append(...nodes);
                    </script>
                

example: using the append() method to append text to an element
code:
                    <div class="spec">
                        <div id="app1"></div>       
                        <div id="app1a" style="color:red"></div>       
                </div>
                <script>
                        let app1 = document.querySelector('#app1');
                        app1.append('append() Text Demo');
                        document.getElementById("app1a").innerHTML = app1.textContent;
                    </script>
                

example: using the append() method to append text to an element

Codes:

                    <div class="spec">
                        <div id="app2"></div>
                        <div id="app2a" style="color:red"></div> 
                    </div>
                    <script>
                        let app2 = document.querySelector('#app2');
                        app2.append('today is a beautiful day');
                        document.getElementById("app2a").innerHTML = app2.textContent;
                    </script> 
                


append() vs. appendChild()

append(): return value undefined; can append several nodes and strings ; accepts node and DOMString as parameter types.

appendChild(): the appended Node object is the return value; can only append a single node; only node as parameter type.

Example: list of subjects

example

Preparing subject list

List of subjects as:

code:
                    <div class="spec">
                        <div class="container">
                            <h4>Preparing subject list </h4>
                            <form>
                                <div class="form-group">
                                    <label for="subjectname">enter subjects:</label>
                                    <input id="subjectname" class="form-control" type="text" 
                                    placeholder="Input the subject name here">
                                </div>
                                <div class="form-group text-center">
                                    <button id="my_button"class="btn btn-outline-success btn-lg" 
                                    type="button">add subjects</button>
                                </div>
                            </form>
                            <h4>List of subjects as:</h4>
                            <div id="listDemo"></div>
                        </div>
                    </div>
                    <script>    
                        function append_to_div(div_name, data){
                            document.getElementById(div_name).innerText += data;
                        }
                        document.getElementById("my_button").addEventListener('click', function() {
                            var user_name = document.getElementById("subjectname");
                            var value = user_name.value.trim();
                            if(value)
                                append_to_div("listDemo", value+"\n");
                            else
                                alert("Please enter subject name!");
                            user_name.value = "";
                        });
                    </script>
                

Example: appending an element (see console)

example
code:
                    <div class="spec">
                        <div id="list"></div>
                    </div>
                    <script>    
                        let parent = document.createElement("div");
                        let p = document.createElement("p");
                        parent.append(p);
                        console.log(parent.childNodes); // NodeList [ <p> ]
                        document.getElementById("list").innerHTML = parent.childNodes;
                    </script>
                

Example: appending an element

example

Lorem ipsum...

Jack!
code:
                    <div class="spec">
                        <div id="box">
                            <p>Lorem ipsum...</p>
                            <div>Jack!</div>
                        </div>
                    </div>
                    <script>  
                        const box = document.getElementById('box')
                        const jack = document.createElement('div')
                        jack.innerHTML = 'Jack!'
                        box.appendChild(jack)
                    </script>
                

Example: demo

example
I was here all along!
I was here all along!
code:
                    <div class="spec">
                        <div id="box1">
                            <div id="preexisting-jack">I was here all along! </div>
                        </div>
                        <div id="box2">
                            <div id="preexisting-jack">I was here all along!</div>
                        </div>
                    </div>
                    <script>    
                        // Append
                        const box1 = document.getElementById('box1');
                        const jack1 = document.createElement("div");
                        jack1.innerHTML = 'Jack1! (I was appended here)';
                        box1.appendChild(jack1);
            
                        // Prepend
                        const box2 = document.getElementById('box2');
                        const jack2 = document.createElement("div");
                        jack2.innerHTML = 'Jack2! (I was prepended here)';
                        box2.insertBefore(jack2, box2.firstChild);
                    </script>
                

Example: add new element to HTML DOM in JavaScript

example

This is an existing element

That is part of the existing DOM

code:
                    <div class=spec>
                        <div id="new">
                            <p id="p1">This is an existing element</p>
                            <p id="p2">That is part of the existing DOM</p>
                        </div>
                    </div>
                    <script>    
                        var tag = document.createElement("p");
                        var text = document.createTextNode("This is the new element that is appended to the DOM.");
                        tag.appendChild(text);
                        var element = document.getElementById("new");
                        element.appendChild(tag);
                    </script>