View Single Post
Old 05-02-2011, 01:16 PM   #13 (permalink)
tony
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

It is because IDs are unique within an html document. If you want to target multiple elements use a class. I know the getElementsByClass method is fairly supported in modern browsers but to make sure you can have a safe-alternate in case the browser doesn't support it. Like the Dustin Diaz method:
javascript Code:
function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}

But if you are going to this lengths and if you are allowed by the project requirements, I would suggest you use jquery or another framework like mootools or any other. They make this stuff easier. For example in jquery:

javascript Code:
$('.unhide').live('click', function (e) {
    $('.hiddendiv').toggle();
});
tony is offline  
Reply With Quote