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

javascript - How to get the count of the DIVs with almost the same ID property? - Stack Overflow

programmeradmin4浏览0评论

I have many DIVs on my page with the same ID

eg:

<div id="myDiv1">
   ...
</div>
<div id="myDiv2">
   ...
</div>
<div id="myDiv3">
   ...
</div>

...

<div id="myDiv20">
   ...
</div>

...

As You see, the ID property looks almost the same - the only diffrence is that there is a number in each ID.

How to get the count of that DIVs? I thought I can do something like that:

var myDivs= document.getElementById('myDiv'); 

but returns null

I have many DIVs on my page with the same ID

eg:

<div id="myDiv1">
   ...
</div>
<div id="myDiv2">
   ...
</div>
<div id="myDiv3">
   ...
</div>

...

<div id="myDiv20">
   ...
</div>

...

As You see, the ID property looks almost the same - the only diffrence is that there is a number in each ID.

How to get the count of that DIVs? I thought I can do something like that:

var myDivs= document.getElementById('myDiv'); 

but returns null

Share Improve this question asked Feb 17, 2010 at 20:59 TonyTony 12.7k38 gold badges129 silver badges232 bronze badges 1
  • And more importantly, why do you need this information for? And would you be able to get the same information without relying on the id attribute? – Romain Commented Feb 17, 2010 at 21:02
Add a ment  | 

4 Answers 4

Reset to default 4

You can do this using jQuery like this:

$('div[id^=myDiv]')

If you can't use jQuery, you'll need to call getElementsByTagName and loop through the values checking the ID property.

var divs = document.getElementsByTagName('div');
var counter = 0;
for(var i in divs) {
    if(divs[i].id.indexOf('myDiv') === 0) {
        counter++;
    }
}

or just

document.querySelectorAll('[id^=myDiv]').length

you can use jquery

//this will give you all divs start with myDiv in the id 
var divs = $("div[id^='myDiv']");

From this site:

function getElementsByRegExpId(p_regexp, p_element, p_tagName) {
        p_element = p_element === undefined ? document : p_element;
        p_tagName = p_tagName === undefined ? '*' : p_tagName;
        var v_return = [];
        var v_inc = 0;
        for(var v_i = 0, v_il = p_element.getElementsByTagName(p_tagName).length; v_i < v_il; v_i++) {
            if(p_element.getElementsByTagName(p_tagName).item(v_i).id && p_element.getElementsByTagName(p_tagName).item(v_i).id.match(p_regexp)) {
                v_return[v_inc] = p_element.getElementsByTagName(p_tagName).item(v_i);
                v_inc++;
            }
        }
        return v_return;
    }

Usage:

var v_array = getElementsByRegExpId(/^myDiv[0-9]{1,2}/);
发布评论

评论列表(0)

  1. 暂无评论