Consider the JavaScript below:
var v;
if (this.children.length > 0) {
v = this.firstElementChild.value;
}
This works in modern versions
this.firstElementChild
should work in every significant browser bar IE <=9 and Firefox 3 (QuirksMode).
this.children[0]
will work in every significant browser bar Firefox 3, except that IE <=9 counts comment nodes as element nodes (QuirksMode). This may or may not be an issue for you.
The catch-all system is this:
var node = this.firstChild,
firstElementChild = null;
for ( ; node; node = node.nextSibling) {
if (node.nodeType === 1) {
firstElementChild = node;
break;
}
}
firstElementChild
will then be the first element child if one exists, null
otherwise. It would be best to see if this.firstElementChild
exists before doing the loop, for performance reasons.
I don't know, maybe this.children[0].value
?
If your code is in an event handler and the function is bound with "attachEvent" the "this" keyword is bound to the "window" object and not the HTMLElement. Try:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
Check http://www.quirksmode.org/js/events_properties.html.