I’m stuck using native DOM methods (I know, right?) and I have a structure like this:
<div>
<input>
<a>
</div>
I’m using an onClick on the <a> tag, and want to retrieve the value from the input. On Chrome/OS X, something like
this.previousSibling.previousSibling.value
will work well. I double it though because the first .previousSibling returns the <div>‘s Textnode, and one more before that gets the input that I want.
My question is: does .previousSibling always return the parent’s text node if it exists?
Thanks!
EDIT / Solution
My hacky solution was (cross browser) to ensure I get the right element looked like this:
var el = this;
while(el.nodeType == 3 || el.tagName && el.tagName !== 'INPUT') {
el = el.previousSibling
};
console.log(el.value);
Location specific, but works cross browser, and is light enough to toss into an onClick for my needs. Thanks for the help in figuring out what was at issue here (line breaks between HTML in particular)
No. It returns the immediately preceding sibling. In your case, there is a text node (a new line) immediately preceding the
aelement, so it returns that.If you remove the white space it should work as expected:
However, that’s not a particularly nice solution. See @Esailija’s answer for a nicer one!