Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an element before another using Javascript?

Tags:

javascript

I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore..

This is my sample:

<div id="container">
 <span id="first">1</span>
 <span id="second">2</span>
 <div id="third">3</div>
 <div id="forth">4</div>
</div>

<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");

bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");

topbar.inserBefore(bmcontainer, boardlist);
</script>

I want to append the span#zero before the span#first. What am I doing wrong? I'm trying to not use jQuery, so I'm looking for a totally javascript solution.


1 Answers

You can use the insertAdjacentElement function.

var boardlist = document.getElementById("first"),
    bmcontainer = document.createElement("span");
    bmcontainer.setAttribute("id", "zero");

    boardlist.insertAdjacentElement('beforebegin', bmcontainer);

Element.insertAdjacentElement

like image 123
andre mcgruder Avatar answered Nov 09 '25 19:11

andre mcgruder