Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add innerHTML before an element in JavaScript? [duplicate]

Now I am not talking about creating children or a child node, I literally mean HTML. This is what I want to do:

I have a basic node, for example:

<div id="foo"></div>

And I have a string of HTML, that I want to append before that element (kinda like what innerHTML does, with the difference, that I am obviously putting it before, not inside), e.g.:

"<span>hello, world</span><div></div>Foo<img src="logo.png" />Bar"

Now I want to insert that HTML before the div, so my outcome would be:

<span>hello, world</span><div></div>Foo<img src="logo.png" />Bar<div id="foo"></div>

Is there any way I can do this in JavaScript (without any library)? Thanks!

like image 702
Ood Avatar asked Dec 07 '22 02:12

Ood


2 Answers

The most elegant and shortest solution is to call insertAdjacentHTML on foo with "beforeBegin" and html string as arguments. Pure JS.

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

like image 151
artur grzesiak Avatar answered Jan 01 '23 05:01

artur grzesiak


The easiest way is to use a helper element for the parsing, then grab its contents. Like this:

var foo = document.getElementById("foo");
var parent = foo.parentNode;
var helper = document.createElement('div');
helper.innerHTML = yourHTMLString;
while (helper.firstChild) {
    parent.insertBefore(helper.firstChild, foo);
}

There, we create a temporary helper, then assign the string to it to generate the contents, then move those child nodes (which are a mix of elements and text nodes) into foo's parent node, just in front of foo.

Note that depending on the HTML content, you may need a different helper element. For instance, if the string defined table rows or cells.

Complete example - live copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Inserting Before</title>
</head>
<body>
  <div>Before foo</div>
  <div id="foo"></div>
  <div>After foo</div>
  <script>
    setTimeout(function() {
      var yourHTMLString = "<span>hello, world</span><div></div>Foo<img src=\"logo.png\" />Bar";
      var foo = document.getElementById("foo");
      var parent = foo.parentNode;
      var helper = document.createElement('div');
      helper.innerHTML = yourHTMLString;
      while (helper.firstChild) {
        parent.insertBefore(helper.firstChild, foo);
      }
    }, 500);
  </script>
</body>
</html>
like image 39
T.J. Crowder Avatar answered Jan 01 '23 06:01

T.J. Crowder