C
Csaba2000
I've been thinking the replies to my earlier post. I can attach
a method to a DOM element as below. But instead of
assigning it to each element individually, I would rather
have it as a method of every DOM element (and failing
that, as a method of all javascript objects) - that would
be much more tidy and memory conscious.
What is the proper syntax for this, because I can't seem
to get it to work on either IE 6 or Firefox 1.0.1 with
..prototype, .__prototype__, .__parent__, or
new Closure (that's obsolete, right?) - or is this not doable?
The idea, of course, if I understand things right, would be to
have showMe (and sorry if I'm butchering the terminology) as a
method on the prototype of all DOM elements so the 'this'
will be appropriately bound when the function is entered.
<body onLoad="tryit()"><div
id=myDiv>Placeholder</div>
<script type='text/javascript'>
showId = function() {
try { var base = "This " + this.tagName + " has ";
if (!this.id) alert(base + "no id");
else alert(base + "id: " + this.id); }
catch(e) {alert("elem has no id");}
}
var aAll = document.all || document.getElementsByTagName("*");
for (var idx in aAll) aAll[idx].showId = showId;
function tryit() {
document.body.showId(); // will show This BODY has no id
document.body.childNodes[0].showId(); // will show myDiv
}
</script></body>
Thanks,
Csaba Gabor from Vienna
a method to a DOM element as below. But instead of
assigning it to each element individually, I would rather
have it as a method of every DOM element (and failing
that, as a method of all javascript objects) - that would
be much more tidy and memory conscious.
What is the proper syntax for this, because I can't seem
to get it to work on either IE 6 or Firefox 1.0.1 with
..prototype, .__prototype__, .__parent__, or
new Closure (that's obsolete, right?) - or is this not doable?
The idea, of course, if I understand things right, would be to
have showMe (and sorry if I'm butchering the terminology) as a
method on the prototype of all DOM elements so the 'this'
will be appropriately bound when the function is entered.
<body onLoad="tryit()"><div
id=myDiv>Placeholder</div>
<script type='text/javascript'>
showId = function() {
try { var base = "This " + this.tagName + " has ";
if (!this.id) alert(base + "no id");
else alert(base + "id: " + this.id); }
catch(e) {alert("elem has no id");}
}
var aAll = document.all || document.getElementsByTagName("*");
for (var idx in aAll) aAll[idx].showId = showId;
function tryit() {
document.body.showId(); // will show This BODY has no id
document.body.childNodes[0].showId(); // will show myDiv
}
</script></body>
Thanks,
Csaba Gabor from Vienna