We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

noah on 07/10/07


Tagged

hack DOM oo


Versions (?)


set a nested DOM property with square bracket notation


Published in: JavaScript 


URL: http://onemorebug.com/meme.washer/code_examples/set_a_nested_DOM_property_with_square_bracket_notation.html

This was fun to write. I wonder if nested DOM properties can be set with any of JavaScript's built-in methods?

  1. //set a nested DOM property with square bracket notation
  2.  
  3. function setNestedProperty(obj, propertyName, propertyValue){
  4. var thePointer = obj;
  5. for (var i=0; i<propertyName.length; i++){
  6. alert('Setting the pointer to: ' + thePointer);
  7. //with each iteration we get closer to the property we want to set, until:
  8. if (i == (propertyName.length - 1)){
  9. alert('Accessing the method the pointer points to\n and changing the value of the property named "' + propertyName[i] + '," to: "' + propertyValue +'"');
  10. thePointer[propertyName[i]] = propertyValue;
  11. return;
  12. }
  13. thePointer = thePointer[propertyName[i]];
  14. }
  15. }
  16.  
  17. setNestedProperty(document, ['body','style','backgroundColor'], 'black');

Report this snippet 

You need to login to post a comment.