[英]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.