0

i am developing support chat website, i want to append response of ajax html to after body tag's inner html.

e.g.: append html after h2 tag(here is html of web page.)

function insertAfter(referenceNode, newNode) {                                                           
     referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling);
}

var el = document.createElement("span");
el.innerHTML = "<p>test</p>";
var div = document.getElementsByTagName("body");
insertAfter(div, el);
<html>
      <head>
        <title>script example</title>
      </head>
      <body>
        <h2>here is html of web page.</h2>
      </body>
</html>
Siddharth Rathod
  • 634
  • 1
  • 7
  • 21
  • Does this answer your question? [How to insert an element after another element in JavaScript without using a library?](https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib) – CodyKL Dec 09 '19 at 04:55
  • it showing `Cannot read property 'insertBefore' of undefined`, dude @codyKL – Siddharth Rathod Dec 09 '19 at 05:01
  • Means the element where you want to use this function doesn't exists. Working example: https://jsfiddle.net/yn2awrxp/1/ – CodyKL Dec 09 '19 at 05:12
  • Working with `document.getElementById("bodyTagId")` but not working with `document.getElementsByTagName("body")` i used this script for multiple site so it is not possible for all site have unique id of body tag. is any way to select `` tag Thankyou for your response. – Siddharth Rathod Dec 09 '19 at 05:23
  • try document.body – Professor Abronsius Dec 09 '19 at 07:49

1 Answers1

1

The getElementsByTagName will return an array. So you have to take the first element of the array to get the actual body tag. Something like below

var bodyTag = document.getElementsByTagName("body");
bodyTag[0].append(...);
Aditya
  • 771
  • 5
  • 11
  • Thank you, i understood when i select element by `document.getElementsByTagName` it returns array and `document.getElementById` returns object. :) – Siddharth Rathod Dec 09 '19 at 06:18