我有一个字符串:
var s = '<h1>heading</h1><p>para</p>';
Run Code Online (Sandbox Code Playgroud)
我想从中删除h1元素.我试过了:
$(s).remove('h1');
Run Code Online (Sandbox Code Playgroud)
但仍然包含h1我尝试过的元素:
s = $(s).remove('h1');
Run Code Online (Sandbox Code Playgroud)
和
$('h1', s).remove();
Run Code Online (Sandbox Code Playgroud)
和
$('h1', $(s)).remove();
Run Code Online (Sandbox Code Playgroud)
等等
有任何想法吗?
use*_*716 32
更新:我看到你刚刚改变了问题.现在的解决方案是:
var s = '<h1>heading</h1><p>para</p>';
var $s = $(s).not('h1');
$('body').append($s);?
Run Code Online (Sandbox Code Playgroud)
试一试: http ://jsfiddle.net/q9crX/19/
因为你现在在jQuery对象中有多个"顶级"元素,所以你可以使用.not()(基本上是相反的.filter())删除它h1.
这与做的一样 $(s).filter(':not(h1)');
原始答案
$(s).find('h1').remove();
Run Code Online (Sandbox Code Playgroud)
所以,如果你要将结果附加到body,你可以这样做:
var s = '<div><h1>heading</h1><p>para</p></div>';
var $s = $(s).find('h1').remove().end();
$('body').append($s);?
Run Code Online (Sandbox Code Playgroud)
试一试: http ://jsfiddle.net/q9crX/