3

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?

1
  • insertBefore() is the function you could use. Commented Jul 13, 2017 at 6:23

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Try like this .Better do with createElement() instead of string element creation in dom

parentNode.insertBefore(newnode, existingnode)

var footer = document.querySelector('footer')

var string = document.createElement('div')
string.class='sun'
string.innerHTML ='<p>hi and more things</p>'

document.body.insertBefore(string,footer)
<footer>
  footer
</footer>

2 Comments

Thanks, just curious: Why is it better than using insertAdjacentHTML?
i was mention with element creation not with insert function
1
var fragment = document.createDocumentFragment();
fragment.innerHTML = "<div class='sun'><p>hi and more things</p>...</div>";
var footer = document.querySelector('footer');
document.body.insertBefore(fragment, footer);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.