jQuery 在jquery中选择根元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1650063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selecting root element in jquery
提问by Sqoo
I need to be able to select the root element from a fragmentwithout knowing the node types, class, id or hierachy.
我需要能够在不知道节点类型、类、id 或层次结构的情况下从片段中选择根元素。
<div id="0">
<div id="0a">
<div id="a01"></div>
</div>
<div id="0b">
</div>
<div id="0c">
</div>
</div>
I want to be able to do something like $(':root') and have 0 selected in the example above.
我希望能够执行类似 $(':root') 的操作,并在上面的示例中选择 0。
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.
更好的是,我更喜欢$(':level(0)')
这意味着与上述相同,$(':level(1)')
会选择 0a、0b 和 0c 并$(':level(1)>div')
会选择 a01。
Any ideas on how to do it neatly?
关于如何巧妙地做到这一点的任何想法?
采纳答案by Pebbl
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:
虽然不久前这个问题得到了完美的回答——我只是想自己尝试这个,并不太热衷于使用像这样的选择器*:not(* *)
——主要是因为可能的开销。我不知道这是否是 jQuery 能力的最新添加(我使用的是 1.8),但您可以使用:
$(':eq(0)');
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.
这将选择第一个找到的非 textnode 元素,因此除非您正在遍历的 dom 在其格式中是非法的,否则您应该始终获取根元素。它也是高度优化的,因为 jQuery 应该知道在找到第一个元素后停止。
So here's a little something for all of those WSOD fans out there:
所以这里有一些适合所有 WSOD 粉丝的东西:
$(':eq(0)').remove();
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:
哦,以防万一上面的代码片段只是说明选择器并不明显,并且您发现自己在处理部分片段(而不是完整文档),那么您应该将此选择器与 jQuery 的过滤器方法一起使用:
$(fragment).filter(':eq(0)');
However, when working with fragments you can just do the following:
但是,在使用片段时,您只需执行以下操作:
$(fragment).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.
尽管请记住,.get(0)
如果文本/评论节点是文档中的第一项,则可以选择它们,而过滤器方法将始终找到第一个实际元素。
回答by Deeksy
OK, so what you need to do is the following (presuming that you are using the sample you've got), if you want to find the top level node using jquery is the following:
好的,那么您需要做的是以下(假设您正在使用您拥有的示例),如果您想使用 jquery 查找顶级节点如下:
$('*:not(* *)');
What you are literally asking for here is for all nodes that are not children of other nodes. The problem is that for a html document, this will always give you only the html element, which isn't particularly useful. So, if you want to find the top level element within the body of a html document, you'd use something a lot simpler:
您在这里真正要求的是所有不是其他节点的子节点的节点。问题是对于 html 文档,这将始终只为您提供 html 元素,这不是特别有用。因此,如果您想在 html 文档的正文中找到顶级元素,您可以使用更简单的方法:
$('body > *');
if you then wanted the second level, you'd just go
如果你想要第二级,你就去
$('body > * > *');
But, presuming you have some sort of arbitrary document structure (like the foo one you mention), what you can do is use the first example to find the first level:
但是,假设您有某种任意文档结构(如您提到的 foo ),您可以做的是使用第一个示例来查找第一级:
$('*:not(* *)');
and then for the second level
然后是第二级
$('*:not(* *)').find('> *');
and for the third level
和第三级
$('*:not(* *)').find('> * > *');
and so on and so forth. If you're looking for a root div element (presuming that your sample is like the question), you can do this:
等等等等。如果您正在寻找根 div 元素(假设您的示例与问题类似),您可以这样做:
$('div:not(div div)');
and so on, replacing * with div. Not really sure why you'd want to do this, but it will work. The problem is the question doesn't really provide enough context for us to give you a better alternative.
以此类推,将 * 替换为 div。不确定为什么要这样做,但它会起作用。问题是这个问题并没有真正为我们提供足够的背景来为您提供更好的选择。
回答by Adam Hopkinson
I'm more of a Prototype guy, but I think you could get all the nodes then get the first node in the array:
我更像是一个 Prototype 人,但我认为你可以获取所有节点,然后获取数组中的第一个节点:
$('*')[0]
Then get the child items of that (for 0a, 0b and 0c)
然后获取它的子项(对于 0a、0b 和 0c)
$('*')[0].children()
回答by WiseOwl9000
If you've got your elements as a jQuery fragment like:
如果您将元素作为 jQuery 片段,例如:
var myElements = $('<div id="0">
<div id="0a">
<div id="a01"></div>
</div>
<div id="0b">
</div>
<div id="0c">
</div>
</div>');
then you can find the first element by:
那么你可以通过以下方式找到第一个元素:
myElements.filter(":first")
The filter function looks from the root element of the fragment.
filter 函数从片段的根元素开始查找。
回答by Josh Stodola
jQuery is not needed...
不需要jQuery...
var root = document.firstChild;
回答by Nikolas Stephan
I may be misunderstanding the question, but assuming by root you mean the point at which the parent is a different tag to the child then the following should work.
我可能误解了这个问题,但假设你的根是指父母与孩子不同的标签,那么以下应该有效。
function GetRoot(element) {
while(element.parent().attr("tagName") == element.attr("tagName")) {
element = element.parent();
}
return element;
}
This basically walks up the tree until it finds a parent that is a different tag and then returns the item. For your example that would mean that if your element was in a , , or whatever it would detect it as the root and return it.
这基本上沿着树向上走,直到找到一个不同标签的父项,然后返回该项目。对于您的示例,这意味着如果您的元素在 a 、 或其他任何内容中,它会将其检测为根并返回它。
Making a custom jquery selector with this should be possible too, but is obviously more complicated.
使用它制作自定义 jquery 选择器也应该是可能的,但显然更复杂。
It should also be fairly easy to extend this to take an integer that defines the level. All you'd need to do is walk down the tree to the specified depth once you've found the root and return those elements.
将其扩展为采用定义级别的整数也应该相当容易。一旦找到根并返回这些元素,您需要做的就是沿着树向下走到指定的深度。
回答by lulalala
I get html fragment from ajax call, and I also need to get the root div from it. What I did was simply call $(data)
, and jQuery will parse the returning text as HTML and give you the root.
我从 ajax 调用中获取 html 片段,我还需要从中获取根 div。我所做的只是调用$(data)
,jQuery 会将返回的文本解析为 HTML 并为您提供根。
$.ajax path,
type: 'GET'
contentType: 'application/x-www-form-urlencoded;charset=UTF-8'
success: (data) ->
$(data)
回答by Dsl Diesel
If you want to select the top level parent of an element but still under the body, I'd go
如果你想选择一个元素的顶级父级但仍然在身体之下,我会去
$(obj).parents().filter('body > *')
回答by GSto
you could look into using the parent() and children() functions. is you need to go multiple levels , you can chain them like so.
您可以考虑使用 parent() 和 children() 函数。您是否需要去多个级别,您可以像这样链接它们。
$("#a01").parent().parent() //returns <div id="0">
please see my comment, and I'll try to give a better solution.
请查看我的评论,我会尝试提供更好的解决方案。