[英]Jquery remove everything except for bolded
I have html like this: 我有这样的HTML:
<div id="divTestArea1">
<b>Bold text</b>
<i>Italic text</i>
<div id="divTestArea2">
<b>Bold text 2</b>
<i>Italic text 2</i>
<div>
<b>Bold text 3</b>
</div>
</div>
and I would like to remove all elements that aren't bold. 我想删除所有非粗体的元素。 I've tried with this code: 我试过这段代码:
$('*:not(b)').remove();
and a couple other variations but they all either error out or remove everything. 以及其他一些变化,但它们都会出错或删除所有内容。 btw, are jquery selectors and jsoup selectors 100% compatible? 顺便说一下,jquery选择器和jsoup选择器是否100%兼容? I'd like to use the answer to this in jsoup as well. 我也想在jsoup中使用这个答案。
Your current code removes the document <body>
as well as all <div>
s which contain the <b>
tags. 您当前的代码删除了文档<body>
以及包含<b>
标记的所有<div>
。 If you only want to save the bold text then Shih-En Chou's solution works well. 如果您只想保存粗体文本,那么Shih-En Chou的解决方案效果很好。 If you want to save the <div>
structure that the <b>
tags are in as well you could do this: 如果你想保存<b>
标签所在的<div>
结构,你可以这样做:
$("body *:not(div, b)").remove();
My solution: 我的解决方案
I clone <b>
and save it into memory. 我克隆<b>
并将其保存到内存中。 ->Remove all -> insert <b>
into <body>
- >全部删除 - >将<b>
插入<body>
here is my code: http://jsfiddle.net/sechou/43ENq/ 这是我的代码: http : //jsfiddle.net/sechou/43ENq/
$(function(){
var tmpB = $("b").clone();
$('body').remove();
$("body").append(tmpB);
});
Move all elements in #divTestArea2
as it is a div
and will be removed as well to #divTestArea1
, then filter out anything that is'nt a <b>
and remove it : 移动#divTestArea2
所有元素,因为它是div
,也将被删除到#divTestArea1
,然后过滤掉任何不是<b>
并将其删除:
$("#divTestArea1").append($("*", "#divTestArea2")).find('*').filter(function() {
return this.tagName !== 'B';
}).remove();
The above keeps the #divTestArea1
element intact, to remove everything but the <b>
elements, something like : 上面保持#divTestArea1
元素完整,删除除<b>
元素之外的所有元素,如:
$('body').append($('b')).find('*').not('b').remove();
I prefer .detach()
. 我更喜欢.detach()
。
var $body = $("body");
var $b = $("b", $body).detach();
$(":not(b)", $body).remove();
$body.append($b);
This way you don't need to either move or clone anything to overcome the problem of the deletion of the objects wrapping your <b/>
elements. 这样您就不需要移动或克隆任何东西来克服删除包裹<b/>
元素的对象的问题。
Try this: 试试这个:
// Find all the <b> tags and unwrap them so they all become siblings and finally
// remove non <b> siblings
$('body').find('b').unwrap().siblings('*:not(b)').remove();
Demo: http://jsfiddle.net/3f2Hu/ 演示: http : //jsfiddle.net/3f2Hu/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.