在jQuery中选择根元素 [英] selecting root element in jquery

查看:297
本文介绍了在jQuery中选择根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在不知道节点类型,类,id或层次结构的情况下,从片段中选择根元素.

I need to be able to select the root element from a fragment without knowing the node types, class, id or hierachy.

<div id="0">
    <div id="0a">
        <div id="a01"></div>
    </div>
    <div id="0b">
    </div>
    <div id="0c">
    </div>
</div>

我希望能够执行类似$(':root')的操作,并在上面的示例中选择0.

I want to be able to do something like $(':root') and have 0 selected in the example above.

我还是更喜欢$(':level(0)'),它的含义与上面相同,$(':level(1)')选择0a,0b和0c,而$(':level(1)>div')选择a01.

Better still I would prefer $(':level(0)') which would mean the same as above, $(':level(1)') would select 0a, 0b and 0c and $(':level(1)>div') would select a01.

关于如何整齐地做任何想法?

Any ideas on how to do it neatly?

推荐答案

虽然此问题已在不久前得到了正确正确的回答-我只是尝试自己尝试一次,并且并不太热衷于使用*:not(* *)这样的选择器-主要是因为可能的间接费用.我不知道这是否是jQuery功能(我正在使用1.8)的最新功能,但您可以使用:

Whilst this question was answered a while ago perfectly correctly - I was just trying to attempt this myself and wasn't too keen on using a selector like *:not(* *) -- mainly because of the probable overheads. I don't know if this is a recent addition to jQuery's ability (i'm using 1.8) but you can use:

$(':eq(0)');

这将选择第一个找到的非textnode元素,因此,除非您遍历的dom在其形式中是非法的,否则应始终获取root元素.这也是最佳选择,因为jQuery应该知道在找到第一个元素之后停止.

This will select the first found non-textnode element, so unless the dom you are traversing is illegal in it's formation, you should always get the root element. It is also highly optimal because jQuery should know to stop after the first element found.

因此,这里为所有那些WSOD粉丝提供了一些帮助:

So here's a little something for all of those WSOD fans out there:

$(':eq(0)').remove();

哦,以防万一上面的代码片段只是说明选择器,而您发现自己使用了部分片段(而不是整个文档),那么应该将此选择器与jQuery的过滤器一起使用方法:

Oh and just in case it isn't obvious that the above code snippets were just illustrating the selector, and you find yourself working with a partial fragment (rather than the full document), then you should use this selector with jQuery's filter method:

$(fragment).filter(':eq(0)');

但是,使用片段时,您可以执行以下操作:

However, when working with fragments you can just do the following:

$(fragment).get(0);

尽管请记住,.get(0)如果文本/注释节点是文档中的第一项,则可以选择它们,而过滤器方法将始终找到第一个实际元素.

Although bear in mind that .get(0) can select text/comment nodes if they are the first item in your document, whereas the filter approach will always find the first actual element.

这篇关于在jQuery中选择根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆