Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS insertBefore() and pass a string contains html

Tags:

javascript

I am looking for a way how I can insert things before an element in plain javascript.

I have a footer element:

//html
<footer>
  ...
</footer>

// js
var footer = document.querySelector('footer')

and I want to add this string containing html before it:

var string = "<div class='sun'><p>hi and more things</p>...</div>"

In jQuery I'd simply do this:

$(footer).before(string)

But how I can do it in plain javascript? How to convert the string to NODE and then display?

like image 490
Petr Avatar asked May 31 '26 01:05

Petr


1 Answers

You can use .insertAdjacentHTML('beforebegin', string)

var string = "<div class='sun'><p>hi and more things</p>...</div>"

document.querySelector('footer').insertAdjacentHTML('beforebegin', string);
<footer>Footer</footer>
like image 120
Yury Tarabanko Avatar answered Jun 02 '26 20:06

Yury Tarabanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!