Posted By

noah on 06/28/07


Tagged

basic wrapper library DOM utility helper safe easy tools glue sanitycheck


Versions (?)

Safely Get and Operate Upon An Element


 / Published in: JavaScript
 

Pass this an ID or an object reference, as well as any number of functions that take the referenced object as a parameter. This wrapper is intended to provide a sanity check against missing DOM elements.

  1. function safeGet () {
  2. var o;
  3. var ioj = arguments[0];
  4. if (typeof ioj == 'string') {
  5. o = document.getElementById(ioj);
  6. } else {
  7. o = ioj;
  8. }
  9. if (typeof ioj != 'object') return;
  10. for (var i=1; i< arguments.length; i++) {
  11. arguments[i](o);
  12. }
  13. return true;
  14. }
  15.  
  16. //use it like this
  17. safeGet (document.body,
  18. function (o) {
  19. o.style.background='black';
  20. },
  21. function (o) {
  22. o.style.color='white';
  23. }
  24. );
  25. //misuse it like this, but it won't throw an error
  26. safeGet ('someIdThatDontExist',
  27. function (o) {
  28. o.style.background='black';
  29. },
  30. function (o) {
  31. o.style.color='white';
  32. }
  33. );

Report this snippet  

You need to login to post a comment.