this.nextSibling not working

moroccan_dev picture moroccan_dev · Nov 15, 2014 · Viewed 13.6k times · Source

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?

Answer

undefined picture undefined · Nov 15, 2014

nextSibling selects the very next sibling node of the element. The very next node can also be a textNode which doesn't have an id property, hence you get the undefined value. As the other answer suggests you could use the nextElementSibling property which refers to the next sibling node that has nodeType of 1 (i.e. an Element object) or remove the hidden characters between the elements.

Note that IE8 doesn't support the nextElementSibling property.