将元素放在DOM JavaScript中的某个位置

时间:2016-09-06 09:44:45

标签: javascript

我有这个代码创建一个元素,但我面临的问题是它将它附加在页面的最底部,为了使这个工作我需要它定位在DOM中的某个位置怎么能我这样做?

var x  = document.getElementById('options_10528_1');
var pos = document.getElementById('options-10528-list');
x.onclick = function(){
var elem = document.createElement('div');
elem.setAttribute("class","uk-warning");
elem.innerHTML = "Unfortunately, we cannot supply this medicine. Please  consult your GP.";
document.body.appendChild(elem);
}

2 个答案:

答案 0 :(得分:0)

afterWhichNode.parentNode.insertBefore(newNode, afterWhichNode.nextSibling);

此代码将在afterwichNode之后插入一个节点,即使用vanilla javascript,如果您使用的是jquery,只需使用.after()

答案 1 :(得分:0)

目前,您要在body标签中附加元素,它始终位于底部。因此,如果要将元素追加到特定位置,则必须将其附加到该容器中。假设你想把它添加到“pos”中,你可以这样做:

pos.appendChild(elem);