document.getElementById in toString
edit
Found my answers here. Bottom line: toString/valueOf
can only return primitive types. So here the l开发者_运维技巧ack 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
By definition, toString()
return a string. It can't (by design) return complex object.
So, by returning document.getElementById(id)
you return the string [object]
(IE) or [object HTMLDivElement]
(Chrome) - that string has no such property as innerHTML
.
You can do this though:
toString: function(){return document.getElementById(id).innerHTML;},
And it will show the inner HTML of the element.
console.log(myEl.valueOf().innerHTML);
I don't get it, why would following object:
{
set: function(nwid){id = nwid;},
toString: function(){return document.getElementById(id);},
valueOf: function(){return document.getElementById(id);}
}
have a property innerHTML
? It seems you are somehow counting on the toString method being implicitly called but instead of returning a string it returns a DOM object. What on earth are you trying to do?
Why not use jQuery?
$('myID').innerHTML();
精彩评论