Does .previousSibling always always return the parent text of a node?

I am stuck using my own DOM methods (I know, right?), And I have a structure like this:

<div>
    <input>
    <a>
</div>

I use onClick in the tag <a>and want to get the value from the input. On Chrome / OS X, something like

this.previousSibling.previousSibling.value

will work well. I double it because the first .previousSiblingreturns a <div>Textnode, and another one to the one that gets the input I need.

My question is: .previousSiblingalways returns the parent text of the node, if it exists?

Thank!

EDIT / Solution

My hacked solution was (cross-browser) to make sure I get the right item:

var el = this; 
while(el.nodeType == 3 || el.tagName && el.tagName !== 'INPUT') {
    el = el.previousSibling
}; 
console.log(el.value);

, -, , onClick . , ( HTML )

+5
3

.previousSibling node, ?

. . node ( ), a, .

, :

<div>
    <input><a></a> <!-- input is immediately preceding anchor -->
</div>

. . @Esailija !

+5

sibling node, text node, element node, null

.previousElementSibling, , ​​, :

function previousElementSibling( elem ) {

    do {

        elem = elem.previousSibling;

    } while ( elem && elem.nodeType !== 1 );

    return elem;
}

previousElementSibling(this) .

+8

http://www.w3schools.com/dom/prop_element_previoussibling.asp

previousSibling sibling node ( node )

node , null.

, , ,

<div><textnode><input><textnode><a><textnode></div>

... therefore, if browsers follow the rules, it should work properly. If you ask if there are browsers that do not follow the rules on this subject, I cannot help you, but I want to note that IE has the habit of adding dom objects to pages (in particular, like wrappers), which can be dangerous independently .

Edit: http://www.w3schools.com/dom/dom_nodes_navigate.asp have this say on the subject.

Firefox and some other browsers will treat empty white spaces or newlines as text nodes, Internet Explorer will not.

+1
source

All Articles