[英]Get next and previous nodeType
I have the following HTML: 我有以下HTML:
<body>Testing1<span id="t1" style="background-color: green;">Testing2</span>Testing3</body>
When I try the following: 当我尝试以下操作时:
alert(window.jQuery('#t1').prev().nodeType); // undefined - tried get(0) as well
alert(window.jQuery('#t1').get(0).nodeType); // 1
alert(window.jQuery('#t1').next().nodeType); // undefined
Why is it that I get undefined when I try to get the node type of the previous and next text elements? 尝试获取上一个和下一个文本元素的节点类型时,为什么我未定义?
The weird thing is if I put a b
tag before the span, the prev().get(0).nodeType
returns a 1
does that mean text nodes and comments are undetectable?? 奇怪的是,如果我在跨度之前放置
b
标记,则prev().get(0).nodeType
返回1
,这意味着文本节点和注释不可检测吗?
The problem is that prev
and next
return jQuery objects, not DOM elements. 问题是
prev
和next
返回jQuery对象,而不是DOM元素。 You will have to use get
again: 您将不得不再次使用
get
:
alert(window.jQuery('#t1').next().get(0).nodeType);
Note that you can alternatively use array syntax to get the underlying DOM element at the specified index: 请注意,您也可以使用数组语法来获取位于指定索引处的基础DOM元素:
alert(window.jQuery('#t1').next()[0].nodeType);
Edit 编辑
Just re-read your question and saw that you've already tried that. 只需重新阅读您的问题,看看您已经尝试过了。 You are right in thinking that
prev
and next
will not get text or comment nodes. 您正确地认为
prev
和next
将不会获得文本或注释节点。 They will only get elements. 他们只会得到元素。
The text node that precedes #t1
is not an element, so prev
will not return anything (there are no sibling elements preceding or following #t1
). #t1
之前的文本节点不是元素,因此prev
将不会返回任何内容( #t1
之前或之后没有兄弟元素)。
You could do this: 您可以这样做:
alert(window.jQuery('#t1').get(0).previousSibling.nodeType); //3
alert(window.jQuery('#t1').get(0).nextSibling.nodeType); //3
But I'm not entirely sure of the browser compatibility of those. 但是我不确定这些浏览器的兼容性。
You could just use plain js: 您可以只使用普通的js:
alert(document.getElementById('t1').previousSibling.nodeType);
alert(document.getElementById('t1').nextSibling.nodeType);
of course you should check that getElementById returns an element and that there is a next/previousSibling before trying to get its nodeType. 当然,在尝试获取其nodeType之前,您应该检查getElementById返回一个元素,并且存在next / previousSibling。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.