According to this blog post it is possible to reference DOM elements as named properties of the window
object (based on their name
attribute). The above code shows that indeed the form can be accessed as window.aform
. Yet why does it fail to find the property when iterating over all properties of window
?
<html>
<body>
<form name='aform'>
</form>
<script>
// get all properties, including non-enumerable ones: http://stackoverflow.com/a/8024294/274677
function getAllProperties(obj){
var allProps = [], curr = obj;
do {
var props = Object.getOwnPropertyNames(curr)
props.forEach(function(prop){
if (allProps.indexOf(prop) === -1)
allProps.push(prop)
})
} while(curr = Object.getPrototypeOf(curr))
return allProps
}
var findIn = function(x,y) {
var ps = getAllProperties(x);
for (var i = 0 ; i < ps.length; i++) {
var propertyName = ps[i];
try {
if (x[propertyName]===y)
return 'found as property ['+propertyName+']';
} catch (e) {
console.log('failed to read property ['+propertyName+'] due to: ['+e.name+']');
}
}
return "not found";
}
console.log(findIn(window, window.aform));
console.log(window['aform']===window.aform);
console.log(window.aform);
</script>
</body>
</html>
When the above page loads, I see on the console:
not found
true
<form name="aform"></form>