如何选择没有父节点的节点?
我想采用这样的字符串:
<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>
然后删除所有
节点。
我对此感到困难,因为我认为上面的字符串没有上下文,而 JQuery 需要一个上下文来允许选择器工作:
var p = "<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>"
var pj = $(p)
当我在 FireBug 中运行下面的语句时,我没有返回任何元素。这是因为 'p' 变量需要包装在另一个 div 中才能工作吗?我希望能够从字符串中删除元素,即使它不是 DOM 的一部分。
$("p",pj)
I would like to take a string like so:
<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>
and then remove all <p>
nodes.
I'm having difficulty with this because I think that the string above has no context, and JQuery needs a context to work with to allow selectors to work:
var p = "<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>"
var pj = $(p)
When I run the statement below in FireBug, I get no elements returned. Is this because the 'p' variable needs to be wrapped in another div for it to work? I want to be able to strip the elements from the string, even though it is not part of the DOM.
$("p",pj)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要
.filter()
来搜索同一级别的元素,例如这:$("p",pj)
在幕后转换为$(pj).find("p")
,这就是为什么它找不到任何东西,因为元素是
pj
的后代,它们是成员。需要明确的是,jQuery 不需要将它们包含在任何内容中,这是一个后代与非后代的问题。另一种方法是将它们添加到临时片段中并始终使用
.find()
< /a>,像这样:然后
$("p",pj)
就可以了。You need
.filter()
to search elements at the same level, like this:$("p",pj)
translates to$(pj).find("p")
under the covers, that's why it's not finding anything, because the<p>
elements are descendants ofpj
, they're members. To be clear, jQuery doesn't need them to be contained in anything, it's a descendant vs non-descendant issue.The alternative approach is to add them to a temporary fragment and always use
.find()
, like this:Then
$("p",pj)
would work.