需要将span元素追加到DOM。
if (check smth...) {
a = createElement('span');
a.id = '_span';
b = document.getElementById('container');
b.appendChild(a);
}
在“if”中防止从dom树中复制相同元素的最佳方法是什么?它有点 - “打开窗户,在关闭之前不要再做”
答案 0 :(得分:2)
if ( document.getElementById( '_span' ) ) {
// Your code where you're creating your element with id "_span"
}
答案 1 :(得分:1)
添加ID并在添加新元素之前检查是否存在具有给定id的元素。
if($('#element_id').length) {
//do nothing, element is already in the dom
} else {
//add element
}