Access multiple items with same name in DOM

This question already has an answer here:

  • jQuery to loop through elements with the same class 14 answers

  • You can iterate through the collection of items with .each() :

    $(".license-box pre").each(function() {
      console.log("this <pre> contains: " + $(this).text());
    });
    

    The callback to .each() is passed the index, which would let you do something like act only on the even-indexed elements:

    $(".license-box pre").each(function(index) {
      if ((index & 1) === 0)
        console.log("even <pre>: " + $(this).text());
    });
    

    If you know which one you want, you can use .eq() :

    var third = $(".license-box pre").eq(3);
    

    You can do a lot of stuff right in the selector itself. If you want to do something to every 3rd <pre> you could do this:

    $(".license-box pre:nth-child(3n)").each(function() {
      console.log($(this).text());
    });
    

    (The nth-child() selector here would make sense when the <pre> elements are the direct children of the "license-box" container, because the semantics have to do with each element's sibling relationships.)


    Like this? .each

    var res = [];
    
    $(".license-box pre").each(function(){
        res.push($(this).text()); // or alert($(this).text());
    });
    
    console.log(res);
    

    Now, if you want text of n th instance, simply do:

    alert(res[n - 1]);
    
    链接地址: http://www.djcxy.com/p/83504.html

    上一篇: 将检查的项目的类名称查询为数组?

    下一篇: 在DOM中访问多个具有相同名称的项目