2014-01-17 31 views
2

我想從DOM中刪除元素使用ID一個.remove()不從DOM

HTML

<div id="no-js"> 
    Sorry for the inconvenience<br/> 
    Your browser does not support javascript or it must be disabled.<br/> 
    To access the features of our website<br/><br/> 
    Enable your javascript or upgrade to the browser that supports javascript. 
</div> 

jQuery的

var x = $("#no-js"); 
console.log(x.html()); 
x.remove(); // does not remove the element from dom why? 
console.log(x.html()); // it displays html content inside it 
console.log(x.length); // results 1 
x.empty(); // removes the child elements, working as expected 
console.log(x.html()); // html content is empty 
console.log(x.length); // length is 1 

刪除元素.remove()似乎沒有按預期工作? 這是小提琴 http://jsfiddle.net/QGsza/14/

回答

3

.remove()從DOM刪除元素,但仍然是變量x持有一個引用它是01的原因返回1

如果測試再次console.log($("#no-js").length)它會給0,因爲它會觸發一個新的DOM搜索和元素已被移除

演示:Fiddle

0

你的選擇是錯誤的,換到$("#no_js")。欲瞭解更多信息,請查詢jQuery API

0

不喜歡,我已經嘗試在你撥弄它正在

var x = $("#no-js").html(); 
x.remove(); 
0

.remove()作品通過去除DOM元素如預期。您可以驗證此如下:

var x = $("#div_no_js"); 
console.log(x[0].parentNode); // returns the <body> element 
x.remove(); 
console.log(x[0].parentNode); // returns null 

刪除的元素仍然存在內存中,他們垃圾清理。只要您有參考,您可以將這些元素添加回DOM。