What is the difference between the append() & appendChild()?

What is the difference between the append() & appendChild()?

What is append()?

The append() method will insert DOMString objects as text nodes. The method has no return value. Let's say you have a ul and you want to add a p tag but only within the js file.

<html>
    <head>
    </head>
    <body>
        <ul id="my-list">
            <li>0</li>
            <li>1</li>
            <li>2</li>
        </ul>

        <script src="index.js"></script>
    </body>
</html>

In your javascript file, you want to create a new paragraph and create a new element. Then you will need to add text to your variable that you created by using textContent and set it to equal whatever you want it to say. Now we need to append it to the document but we do not want to append to our ul we have above. We will need to append it to the body. Luckily we do not need to give the body an id since it's unique.

var newP = document.createElement("p")
newP.textContent = "This is how you will append to the body!"
document.body.append(newP)

.appendChild()

Similar to the .append method, this method is used to elements in the DOM, but in this case, only accepts a Node object.

// Lets say you are inserting a Node object. How would you do that? Remember the differences between the parent and the child. In the HTML file the <body> is the parent and the <ul> is the child. So, let's dive into the code.
// creating another div which will add it into the HTML file
const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
// the child element will append to the div element
// if you console.log the terminal will show the following <div><p></p></div>

What are the differences?

Screen Shot 2021-03-16 at 9.56.52 AM.png

Conclusion

In cases where you can use .appendChild, you can use .append but not vice versa. Use the parentNode.append() method to append a set of Node objects or DOMString objects after the last child node of the parentNode.