insertAdjacentText() in javascript

insertAdjacentText() method in javascript

insertAdjacentText() method is used to insert new text at a specific position.

Position can be represented using following values,

  • 'beforebegin' : Insert the text before the specified element.
  • 'afterbegin' : Insert the text inside the specified element, but before its first child.
  • 'beforeend' : Insert the text inside the specified element, but after its last child.
  • 'afterend' : Insert the text after the specified element.

Example - Add new Text

Try Yourself

Example Explanation

  • In the above example we have added a paragraph and created two buttons and two Javascript functions are declared for those buttons (fun_before(), fun_after()).
  • When the button is clicked Javascript function is called.
  • If the first button is clicked, fun_before() is called. In here it adds the text just above the paragraph.
  • If the second button is clicked, fun_after() is called. In here it adds the text just after the paragraph.