I expect the following code to alert "out"
<input type=text onfocus="alert(this.nextSibling.id)" />
<output id="out">this is output</output>
But it alerts undefined WHY?
I expect the following code to alert "out"
<input type=text onfocus="alert(this.nextSibling.id)" />
<output id="out">this is output</output>
But it alerts undefined WHY?
Note that
this.nextSibling
might not work in IE specificallyThe
jQuery
alternative forthis.nextSibling
is$(this).next()
Why you have this problem
nextSibling
selects the next sibling node of the element. In your case you have a text node as a next node because you have a new line between your element nodes. Each text node between element nodes will be selected as next node and this nodes don't have anid
property.To prevent this we can use 2 ways:
Solution 1:
We delete a new lines, all of whitespaces, comment nodes or other text nodes and then we can use
nextSibling
:Solution 2:
We use instead of
nextSibling
thenextElementSibling
property:The
nextElementSibling
property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.In the case if some browser like IE8 doesn't support the
nextElementSibling
property we can use a polyfill (it should be placed before your code):Relevant links:
Node.nextSibling
NonDocumentTypeChildNode.nextElementSibling
Try this:
NOTE: The
nextSibling
property returns the node immediately following the specified node, in the same tree level.The
nextElementSibling
read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.nextSibling
selects the very next sibling node of the element. The very next node can also be atextNode
which doesn't have anid
property, hence you get theundefined
value. As the other answer suggests you could use thenextElementSibling
property which refers to the next sibling node that hasnodeType
of1
(i.e. an Element object) or remove the hidden characters between the elements.Note that IE8 doesn't support the
nextElementSibling
property.