[英]How to remove all elements except for one, maintaing the same CSS path to it?
我需要從頁面中提取單個元素(及其所有內容),但仍保持指向該元素的相同CSS樹。
為了說明,假設我具有以下DOM:
<div>1
<div>2</div>
<div>3
<div>4
<div>5</div>
</div>6
<div>7
<div>8
<div>9</div>
</div>
</div>
<div>10
<div>
<div>content</div>
</div>
</div>
</div>
</div>
我只對包含content
的元素感興趣,即我需要將DOM轉換為:
<div>
<div></div>
<div>
<div></div>
<div></div>
<div>
<div>
<div>content</div>
</div>
</div>
</div>
</div>
( content
的路徑應該仍然相同)
我正在這個jsfiddle中嘗試類似的東西:
$("#want").siblings().html("");
$("#want").parents().siblings().html("");
這似乎還不夠。
建議?
編輯:概括示例,可以有任何元素而不是divs。
也許是這樣的:
var classForKeepings = 'keepThisItem';
var $elem = $('#want'); // give start element
$elem.addClass(classForKeepings); // give a class to make it stay
while( $elem.parent().length!==0 ){ // while the element has a parent
$elem = $elem.parent(); // shift $elem to the parent
$elem.addClass(classForKeepings ); // and add a class to make it stay
}
$('#startElement *:not(.'+classForKeepings+')').remove(); // remove all elements not tagged with the class
$('.'+classForKeepings ).removeClass(classForKeepings); // Cleanup afterwards
我使用了remove,因為您不需要它們。 如果確實需要這些,可以將其更改為.html('')
使用這個sintax
$(function(){
$("div:not(#want)").contents().filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
});
希望能幫助到你。
這似乎正在工作..太糟糕了,我需要它與Cheerio一起工作,但是似乎沒有content contents()
..猜測我將不得不使用jsdom來代替..如果找不到其他解決方案..
$("#want").siblings().html("");
$("#want").parents().siblings().html("");
var want = $("#want").clone();
$("*").contents().filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
$("#want").replaceWith(want);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.