简体   繁体   中英

How to append an element before another using 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.

Prepend pure javascript

MDN article on insertBefore()

var el = document.getElementById('thingy'),
    elChild = document.createElement('div');
elChild.innerHTML = 'Content';

// Prepend it
el.insertBefore(elChild, el.firstChild);

Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend

Also, the jQuery prepend() Method

You can read about it here and here .

Node.insertBefore() is the answer.

var insertedNode = parentNode.insertBefore(newNode, referenceNode);

If you have Parent Node , then you should use ParentNode.prepend()

ParentNode.prepend(nodesToPrepend);

Take a look @ mentioned links for full documentation and examples.

Update

You have some issues in your code ( typo and wrong usage of innerHTML ), here is fixed code.

HTML

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

JS

var topbar = document.getElementById("container"),
    boardlist = document.getElementById("first"),
    bmcontainer = document.createElement("span");

bmcontainer.setAttribute("id", "zero");   
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property

topbar.insertBefore(bmcontainer, boardlist);

jsfiddle

Notice that InnerHTML is not a function , it's a property , read more about that here: Element.innerHTML

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM