Count variable ids in getElementById

Hi

Can anyone please help me with a little problem. On my HTML page I have a variable number of divs, all of which have an id of tab1, tab2, tab3 etc (unique to each div). Also on the page are other divs which are unrelated.

I need javascript to count the number of divs which have ‘tab’ as part of their id. So far, I only have a count of the total number of divs, using:

var divCounter = 0;
function divCount() {
if (document.getElementsByTagName&&(divs=
document.getElementsByTagName(‘div’))) {
for (var i=0; i < divs.length; i++)

	divCounter += 1;

}
return divCounter;

}

and calling the function in the body tag using onload.

I am trying to use something like:

var notabs=0;
for (var m=1; m < divCounter; m++) {
if (document.getElementById.indexOf(‘tab’)!=-1) {notabs++;}
}

but it doesn’t like the indexOf (error as from Firefox using the developer toolbar):

Error: document.getElementById.indexOf is not a function

I need to get the exact number of divs with an id of 'tab’x rather than the total number of divs as it gives me a javascript error when I try and use that figure in another function. It is not the other function at fault because if I hard code the number of divs with 'tab’x then it all works fine.

Does anyone have any ideas please?

document.getElementById is a function that returns an element. It is not the id string. You should be doing:

var divs = document.getElementsByTagName('div');
var numTabs = 0;
for (var i = 0; i < divs.length; i++) {
	if (divs[i].id.indexOf('tab') != -1)
		numTabs++;
}

Thank you. That is brilliant and just what I needed :wink: