document.getElementById in toString

Posted by KooiInc on Stack Overflow See other posts from Stack Overflow or by KooiInc
Published on 2010-12-26T14:14:20Z Indexed on 2010/12/26 14:54 UTC
Read the original article Hit count: 270

Filed under:
|
|

edit Found my answers here. Bottom line: toString/valueOf can only return primitive types. So here the lack of native getters in javascript shows, I suppose.

I would like to use the following simple function in an elementwrapper:

function ElGetter(id){
       var id = id;
       return {
         set: function(nwid){id = nwid;},
         toString: function(){return document.getElementById(id);},
         valueOf: function(){return document.getElementById(id);}
       };
}
var myEl = ElGetter('myId');
console.log(myEl.innerHTML); //=> undefined

But I can't get it to work. Is it a DOM/javascript restriction or am I missing something? Normally it works, as in:

function Tester(){
    var x = 1;
    return {
   toString: function(){return x},
   valueOf: function(){return x}
 }
}
var myTest = Tester();
console.log(myTest); //=> 1

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about tostring