I have the following 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??
The problem is that
prevandnextreturn jQuery objects, not DOM elements. You will have to usegetagain:Note that you can alternatively use array syntax to get the underlying DOM element at the specified index:
Edit
Just re-read your question and saw that you’ve already tried that. You are right in thinking that
prevandnextwill not get text or comment nodes. They will only get elements.The text node that precedes
#t1is not an element, soprevwill not return anything (there are no sibling elements preceding or following#t1).You could do this:
But I’m not entirely sure of the browser compatibility of those.