2012-04-18 37 views
0

需要将span元素附加到DOM。防止在dom树中收集相同元素的最佳方法?

if (check smth...) { 

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

} 

什么是最好的方法来做“if”以防止从dom树中复制相同的元素?它是有点儿 - “打开窗口并再次,直到它被关闭不这样做”

+0

什么是“d”我在这里看不到? – 2012-04-18 19:21:24

+0

@Mark Schultheiss纠正 – 2012-04-19 04:59:05

回答

2
if (document.getElementById('_span')) { 
    // Your code where you're creating your element with id "_span" 
} 
1

把一个ID,并加入了新的元素检查,如果存在与给定id的元素之前。

if($('#element_id').length) { 
    //do nothing, element is already in the dom 
} else { 
    //add element 
}