0

需要将 span 元素附加到 DOM。

if (check smth...) {

    a = createElement('span');
    a.id = '_span';
    b = document.getElementById('container');
    b.appendChild(a);

}

在“if”中防止从 dom 树复制相同元素的最佳方法是什么?有点 - “打开窗户,在它关闭之前不要再这样做了”

4

2 回答 2

2
if ( document.getElementById( '_span' ) ) {
    // Your code where you're creating your element with id "_span"
}
于 2012-04-18T19:22:29.283 回答
1

放置一个 ID 并在添加新元素之前检查是否存在具有给定 ID 的元素。

if($('#element_id').length) {
  //do nothing, element is already in the dom
} else {
  //add element
}
于 2012-04-18T19:22:35.647 回答