Does .previousSibling always return the parent's text node if it exists?
No. It returns the immediately preceding sibling. In your case, there is a text node (a new line) immediately preceding the a
element, so it returns that.
If you remove the white space it should work as expected:
<div>
<input><a></a> <!-- input is immediately preceding anchor -->
</div>
However, that's not a particularly nice solution. See @Esailija's answer for a nicer one!
According to http://www.w3schools.com/dom/prop_element_previoussibling.asp
The previousSibling property returns the previous sibling node (the previous node in the same tree level) of the selected element
If there is no such node, this property returns null.
technically, what you're showing there is
<div><textnode><input><textnode><a><textnode></div>
...so if the browsers are following the rules, it should keep working properly. If you're asking whether or not there are browsers out there that fail to follow the rules on this, I can't help you, but I will note that IE has a habit of adding dom objects to pages (particularly as wrappers) which might prove hazardous regardless.
Edit: http://www.w3schools.com/dom/dom_nodes_navigate.asp has this to say on the topic.
Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.
It returns the previous sibling node, it might be text node
, it might be element node
, it might be null
You can retrieve previous element nodes with .previousElementSibling
which isn't supported in legacy browsers but you can use a function like:
function previousElementSibling( elem ) {
do {
elem = elem.previousSibling;
} while ( elem && elem.nodeType !== 1 );
return elem;
}
previousElementSibling(this)
will result in the input element.