In this example
<form id="form1">
<input type="text" name="style">
</form>
<form id="form2">
<input type="text" name="id">
</form>
you cannot access form1's style declaration or form2's id, since the named inputs shadow the corresponding properties.
The same holds for other properties too
Any workarounds?
Edit:
getAttribute
works for id
, obviously. 开发者_如何学编程But not for style
, childNodes
, tagName
etc.
I'm looking for something like this:
getDomProp = (function() {
if (window.__lookupGetter__) {
var cleanForm = document.createElement('form');
return function(form, key) {
// works in Firefox, fails in Opera:
return cleanForm.__lookupGetter__(key).call(form);
};
} else if (Object.getOwnPropertyDescriptor) {
return function(form, key) {
// does not work at all:
// return Object.getOwnPropertyDescriptor(cleanForm, key).get.call(form);
}
} else {
throw 'Not supported.';
}
})();
Fiddle
This will still work:
form.getAttribute('id');
PS. Don't name your inputs that in production code :)
Use getAttribute
to get the corresponding form attributes: http://jsfiddle.net/6d8sx/3/
alert('id: ' + form.getAttribute('id'));
Edit: getAttribute
seems to work in IE9, FF5 (not sure about others).
However, naming your elements that way will cause problems down the line (if not your code, then some library or plugin might get confused).
Access them using .getAttribute();
http://reference.sitepoint.com/javascript/Element/getAttribute
yuse jquery: $('#form1').css()
, or $('#form2').attr('id')
.
精彩评论