Thursday, 27 January 2011

Get DOM Elements by Class Name

Do you remember how badly we had to fight for finding elements by class name prior to HTML5? Just to use this API we had to depend on various other javascript frameworks like Prototype, YUI etc.

For example in case of YUI I had to do add the following in the HTML head section:

                <!-- Yahoo YUI 2: Dom Collection -->
                <!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo/yahoo-min.js">
</script>
                <!-- Source file -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/dom/dom-min.js">
</script>  
....and finally to find elements by class name I had to write the following:

  var viracct_posts_eles = YAHOO.util.Dom.getElementsByClassName('viracct_posts');
  

Thanks to HTML5 for bringing this support at the browser level. We no longer need to load these external libraries to avail this facility.

This is how we can find elements by class name in HTML5:

  var viracct_posts_eles = document.getElementsByClassName('viracct_posts');  
  
Very much similar to getElementsByTagName:

  var viracct_apps_eles = document.getElementsByTagName('div');
  
More posts on HTML5 features are coming soon. Stay tuned!

No comments:

Post a Comment