Javascript provides the append()
method which is used to insert some objects like elements, text, etc. The append() method is provided by a JavaScript element. In this tutorial, we examine how to append new text or element into an element.
Append An Element
One of the most popular use cases for the append() method is the ability to add an existing element into an element. In the following example, we create an element and then add this element.
let div = document.createElement("div")
let p = document.createElement("p")
div.append(p)
Append A Text
Another popular case for the append() method is adding text into the element. The text can be directly provided to the append() method as a parameter. In the following example, we add the text “Hello Wisetut” to the div element.
let div = document.createElement("div")
div.append("Hello Wisetut")
Append Text and Element
We can also add text with an element where the provided text is used for this element. In the following example, we set the text of the element p and add it to the div.
let div = document.createElement("div")
let p = document.createElement("p")
div.append("Hello Wisetut",p)
Append Multiple Elements or Text
Multiple elements can be added using the append() method.
let div = document.createElement("div")
let p = document.createElement("p")
div.append("Hello Wisetut",p)
append() ve appendChild()
There is also a method named appendChild() which can be used to add elements or text. But there are some differences which are described below.
Differences | append() | appendChild() |
---|---|---|
Return value | undefined (No Return Values) | The appended Node object |
Input | Multiple Node Objects | Single Node object |
Parameter Types | Accept Node and DOMString | Only Node |