I’m looking for a way to add a javascript object to the DOM without redefining the object.
I have created a function that puts all object methods into a new object, redefines the object as a new DOM element, and puts all the objects back onto it but this is not exactly what I want. I need the object to be updated without using any return statements.
I have an example here: http://jsfiddle.net/y56wS/
function addToDOM(obj) {
temp = {};
for (p in obj) {
temp[p] = obj[p];
}
obj = document.createElement('prop');
document.body.appendChild(obj);
for (p in temp) {
obj[p] = temp[p];
}
return obj;
}
var obj = {var1:123};
obj = addToDOM(obj);
The resulting code template should be something like this:
function addToDOM(obj) {
//Code for method
//No return statement
}
var obj = {var1:123};
//No obj=
addToDOM(obj);
To accomplish this, there really has to be no obj = within the addToDOM function so that it is never redefined and there is no need for a return statement. Is there a way to simply extend the javascript object onto the DOM?
No, JavaScript objects can’t be added to the document just like that – the
appendChild()method is expecting objects of certain type, usually created withdocument.createElement()method.So you must create new DOM element, or clone existing one, every time.
Assuming you want to have sort of “template” element I suggest using global variable to hold that element, create it once then clone it every time and put the new attributes.
Code for that would be:
As you see, you can pass the object directly to the function no need to assign it to variable first.
Also, to have the object properties applied in the DOM element you have to use
setAttribute()otherwise those properties won’t be part of the DOM.In the above code, the template has the same class for all instances, so you can apply some CSS to affect them all e.g.
Live test case.