Here is the code:
I am trying to get collection.prototype.add to return a reference such that the final alert will display testing, testing, 123, testing. Is there a way to accomplish what I’m trying to do here?
HTML:
<span id="spantest">testing, testing, 123, testing</span>
JavaScript:
var collection = function () {
this.items = {};
}
collection.prototype.add = function(sElmtId) {
this.items[sElmtId] = {};
return this.items[sElmtId];
}
collection.prototype.bind = function() {
for (var sElmtId in this.items) {
this.items[sElmtId] = document.getElementById(sElmtId);
}
}
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);
You problem is this line:
This overwrites the object currently assigned to
this.items[sElmtId]with the DOM node. Instead, you should assign the node to a property of that object:That way,
obj.nodewill always refer to the current node:DEMO
Side note: The problem with your fiddle is also that you execute the code when the DOM is not built yet (
no wrap (head)), so it cannot find#spantest. You have to run the code once the DOM is ready, eitherno wrap (body),onDomReadoronLoad.