views:

235

answers:

7

Hi,

i have 5 div's of the same class but different id stacking on top of each other. how do I traverse them using javascript? they are named div1, div2, div3, etc...

also, how do i change each div's attribute while traversing?

thank you very much.

tam.

+1  A: 

First of all read this article

getElementsByClassName Speed Comparison

and

Enhanced getElementsByClassName

var elements = document.getElementsByTagName("div");

for ( var i = 0; len = elements.length; i < len; i ++ )
{
    if ( elements[i].className === "yourclassname" )
    {
        // change the desired attribute of element.
        //Eg elements[i].style.display = "none";
    }
}

Using jQuery each function

$(".yourclassname").each ( function() {
    // $(this) will fetch the current element
});
rahul
Actually I'd say getElementsByTagName would be faster at this.
cletus
@cletus Depends on the markup
Justin Johnson
@pheonix `document.getElementsByClassName` is FF only
Justin Johnson
Edited my post.
rahul
+2  A: 
for(var i = 1; i++; i<=5){
    var div = document.getElementById("div" + i);
    //do stuff with div
}

Edit: I see you call it "named" div1...div5, you must give id="div1" also for it to work

Esben Skov Pedersen
+4  A: 

In modern browsers you can get them by using the getElementsByClassName function:

var elements = document.getElementsByClassName('myClass');

for (var i = 0, n = elements.length; i < n; i++) {
  //..
}

Notice that I'm getting the elements.length only once, that is a common practice when iterating HTMLCollections.

That's because those collections are "live", they can change at any time, and accessing the length property on each iteration it's expensive.

For complete cross-browser implementations, check this article by Mr. Resig:

Edit: I leave you here a refactored version of the Dustin Diaz getElementsByClassName cross-browser pure DOM Implementation:

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);
  }
}
CMS
-1 For incompatibility: `document.getElementsByClassName` is FF only.
Justin Johnson
@Justin: agree, for that I just added a link where multiple cross-browser implementations are discussed.
CMS
By the way, getElementsByClassName() is not FF only, is now natively supported by the most recent versions of Firefox, Safari, and Opera... http://www.quirksmode.org/blog/archives/2008/05/getelementsbycl.html
CMS
Good to know, -1 +1. Just out of curiosity, why did you refactor Diaz's implementation and how does it compare as far as performance is concerned?
Justin Johnson
@Justin: I refactored to nest the function in the else statement, also stripped out the `tag` argument, that was used to constraint the search to an specific tag, also added the `i` and `j` variables to the var declaration statement, since they were global...
CMS
+1  A: 

Are you using anything like Prototype or jQuery? If so, I highly recommend one of those, as they make traversal quite easy. For example, with Prototype it would be:

$$('.className').each(function(s) {
    //what you want to do
});
Eric
+1  A: 

The library based answers are obvious, but if you're restricted from using them, here are a couple methods that are more compatible than using Firefox's (new and glorious!) document.getElementsByClassName.

Justin Johnson
A: 

Here's a jQuery solution:

Set attributes of all divs:

$(".yourclassname").attr("attribute","value");

Set text content of all divs:

$(".yourclassname").text("New content");

Set html content of all divs:

$(".yourclassname").html("<h1>New content</h1><p>blah blah blah</p>");

The jQuery library can be found at http://jquery.com/.

Eric
+1  A: 

Its a bit of work to hack through, but here is an article on how to enable queryselectorAll even in old browsers:

http://ajaxian.com/archives/creating-a-queryselector-for-ie-that-runs-at-native-speed

To do this in Mootools or Prototype:

 $$('.className').each(function(element, index) {
   //what you want to do
 });

In Jquery it is the same sans the double dollar (as posted by others):

 $('.className').each(function() {
   //what you want to do
 });
SamGoody