1

My document contains a text node with a span node after it. In the Chrome inspector, the text node's nextSibling object is the span node. However, calling textnode.next() returns 0 objects. I'm not adding a selector to the next call and seemingly identical situations throughout the code all work as expected.

Here's what the relevant DOM tree looks like:

<span id="parent-node">
  some text
  <span id="sibling-node">the span's text</span>
  more text
</span>

Why would calling next() on the "some text" node not return the "sibling-node" span?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Jack
  • 85
  • 1
  • 3
  • 1
    Selecting a textnode playing around with it is always problematic. Why don't you select the `span` directly if it has an id? – ShankarSangoli Feb 01 '12 at 05:02
  • jQuery doesn't generally operate on text nodes. It works on elements. For example, `next()` skips right over text nodes and ignored them. – jfriend00 Feb 01 '12 at 05:10

1 Answers1

0

From the docs...

Given a jQuery object that represents a set of DOM elements, the .next() method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements.

So according to the docs, it is expected that .next() is called from an element node, not just any node.

Calling from a text node isn't supported.

  • I wasn't aware text elements weren't part of the DOM. Thanks for the clarification. Is there an efficient fix? I can obviously call parent() and search for the text node and then get the next element in the sibling list, but that seems unnecessarily time consuming. – Jack Feb 01 '12 at 05:09
  • @Jack: They are part of the DOM, but they're not DOM elements. An "element" is specifically a Type 1 DOM node, while a text node is a Type 3 node. The fix would probably just be to use the native `nextSibling` instead of a jQuery method. –  Feb 01 '12 at 05:11