append() in javascript

append() method in javascript

append() method is used to append or join the text to the given element.

Example - Appending text to the given element

Try Yourself

Example Explanation

  • In the above example we have two div element one inside another (idDiv1, idDiv2), button and a Javascript function is declared for it (fun_name();).
  • When the button is clicked Javascript function is called.
  • In the Javascript function, first we are getting the child div element (document.getElementById("idDiv2");) and storing in elem variable.
  • In the next step using append() method we are adding some text to the given element (elem.append("New Content");).
  • Then we are getting the parent div element (document.getElementById("idDiv1");) and storing in elem2 variable.
  • Finally using the alert method, we are displaying the whole parent content, including the text we added (alert(elem2.outerHTML);).