Counting div elements based on id

前端 未结 2 1614
鱼传尺愫
鱼传尺愫 2021-01-29 05:02

I have a page similar to:

相关标签:
2条回答
  • 2021-01-29 05:21

    jQuery:

    $("div[id]").filter(function() {
        return !(/^box:content:\d+:text$/.test(this.id));
    }).size();
    

    Pure JavaScript:

    var elems = document.getElementsByTagName("div"),
        count = 0;
    for (var i=0, n=elems.length; i<n; ++i) {
        if (typeof elems[i].id == "string" && /^box:content:\d+:text$/.test(this.id)) {
            ++count;
        }
    }
    
    0 讨论(0)
  • 2021-01-29 05:31

    To expand on Boldewyn's comment, you can provide multiple classes delimited by spaces, and then work with those classes separately or in combination.

    This probably removes the need for the ids, but I've left them in just in case:

    <div id="content">
    <div id="boxes">
      <div id="box:content:1:text" class="box content 1 text" />
      <div id="box:content:2:text" class="box content 2 text" />
      <div id="another_id" />
      <div id="box:content:5:text" class="box content 5 text" />
    </div>
    </div>
    


    And then with jQuery you can count just the desired items with:

    $j('#content>#boxes>.box.content.text').length
    

    (or perhaps just use '#boxes>.box.text' or whatever works for what you're trying to match)

    0 讨论(0)
提交回复
热议问题