开发者

How to get the count of the DIVs with almost the same ID property?

开发者 https://www.devze.com 2022-12-20 06:52 出处:网络
I have many DIVs on my page with the same ID eg:开发者_开发技巧 <div id=\"myDiv1\"> ... </div>

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号