before() in javascript

before() method in javascript

before() method is used to insert element or text before the given element.

Example - Inserting text before 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 before() method we are adding some text before the given element (elem.before("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);).