最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - traversing div's of the same class - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Sep 16, 2009 at 6:09 Tam N.Tam N. 2,7379 gold badges30 silver badges29 bronze badges 3
  • For cross browser patability and speed use jQuery. – rahul Commented Sep 16, 2009 at 6:27
  • jQuery is definitely the way to go. – Eric Commented Sep 16, 2009 at 6:31
  • Both Mootools and JQuery allow usage of all CSS3 selectors, and Mootools selector engine is just a tad faster than Sizzle's - not enough to warrant switching to just for that (though I feel Mootools is easier to use overall). – SamGoody Commented Sep 16, 2009 at 6:56
Add a ment  | 

7 Answers 7

Reset to default 4

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 mon 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 plete cross-browser implementations, check this article by Mr. Resig:

  • getElementsByClassName Speed Comparison

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);
  }
}
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

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
});

Are you using anything like Prototype or jQuery? If so, I highly remend 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
});

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

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

http://ajaxian./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
 });

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./.

发布评论

评论列表(0)

  1. 暂无评论