/ Published in: JavaScript
This was fun to write. I wonder if nested DOM properties can be set with any of JavaScript's built-in methods?
Expand |
Embed | Plain Text
//set a nested DOM property with square bracket notation function setNestedProperty(obj, propertyName, propertyValue){ var thePointer = obj; for (var i=0; i<propertyName.length; i++){ alert('Setting the pointer to: ' + thePointer); //with each iteration we get closer to the property we want to set, until: if (i == (propertyName.length - 1)){ alert('Accessing the method the pointer points to\n and changing the value of the property named "' + propertyName[i] + '," to: "' + propertyValue +'"'); thePointer[propertyName[i]] = propertyValue; return; } thePointer = thePointer[propertyName[i]]; } } setNestedProperty(document, ['body','style','backgroundColor'], 'black');
You need to login to post a comment.
