简体   繁体   中英

javascript: how to append div in “begining” of another div

I have a div and i want to append another div inside it. but, by using appendChild() it always insert DOM element in end of container element.but i want to insert it in starting of container div .
How to achieve this ?

var newDiv= document.createElement('div');
newDiv.innerHTML = "<input type='text'/>";
var item = document.getElementById('containerDivId');
item.appendChild(newDiv);`

prepend() is what u need..

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

 item.prepend(newDiv);

Since you've included jquery tag... You can use prepend() method.

Or you could use pure JS insertBefore :

item.insertBefore(newDiv, item.firstChild);

使用'item.insertBefore(newDiv,item.firstChild);'

You can use prepend function in jQuery. For example,

$(item).prepend(newDiv);

我认为您可以找到insertBefore

parentElem.insertBefore(insertedElem, parentElem.firstChild);

You can use prepend() on the parent element to add a child first.

http://api.jquery.com/prepend/

I don't have time to test it, but i think that will work.

var newDiv= document.createElement('div');
    newDiv.innerHTML = "<input type='text'/>";
var item = document.getElementById('containerDivId');
    item.prepend(newDiv);

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