Get DOM element via class and id selector, using Google Closure


/ Published in: JavaScript
Save to your folder(s)

The Google Closure lets you get DOM elements with getElement( id ) and getElementByClass( class ). This function combines the two to let you get elements similarly to the way jQuery does. E.g. getElement( '#home .sidebar #links') returns the element with an id of 'links', within the element of class 'sidebar', within the element of id 'home'.


Copy this code and paste it in your HTML
  1. function getElement( selector ) {
  2. var split = selector.split(" ");
  3. var el = document;
  4. var len = split.length;
  5. var type, name;
  6. for( var i = 0; i < len; i++ ) {
  7. try {
  8. name = split[ i ];
  9. type = name[ 0 ];
  10. name = name.substr( 1, name.length - 1 );
  11. switch( type ) {
  12. case "#":
  13. el = goog.dom.getElement( name, el );
  14. break;
  15. case ".":
  16. el = goog.dom.getElementByClass( name, el );
  17. break;
  18. default:
  19. el = null;
  20. }
  21. } catch( e ) {
  22. el = null;
  23. throw( "Error with getElement using selector: " + selector + ", error: " + e );
  24. }
  25. }
  26. if ( el == document ) el = null;
  27. return el;
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.