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!
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With