tags:

views:

77

answers:

4

Hi, 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

+4  A: 

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.

SLaks
You might consider updating the jQuery link to point to the selectors page, since that's the most relevant page to the question. (http://api.jquery.com/category/selectors/)
Seth Petry-Johnson
+1  A: 

you can use jquery

//this will give you all divs start with myDiv in the id 
var divs = $("div[id^='myDiv']");
Amgad Fahmi
You shouldn't use an `@` sign.
SLaks
yeah that's right , fast typing problems :)
Amgad Fahmi
+3  A: 
var divs = document.getElementsByTagName('div');
var counter = 0;
for(var i in divs) {
    if(divs[i].id.indexOf('myDiv') === 0) {
        counter++;
    }
}
chelmertz
it works, but if another myDiv is added, the 'counter' has still the same value. The code seems not to see the dynamically added myDiv
Tony
Then run it again.
Eli Grey
chelmertz
A: 

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