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>