views:

56

answers:

2

hi suppose i have

what i want is inside maindiv i want to count no of elements(may be div input tags)present. there may be use of getElementByTagName(). But the problem is that how to count element.

Thanks

+4  A: 

I think you want getElementsByTagName() rather than getElementByTagName().

That function, given the appropriate parameter, will return a list of all the elements of that particular tag name (divs, p's, etc.)

On every list is a property .length, which will give you the count.

From mozilla docs:

// check the alignment on a number of cells in a table. 
var table = document.getElementById("forecast-table"); 
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
    var status = cells[i].getAttribute("data-status"); 
    if ( status == "open" ) { 
        // grab the data 
    }
}

And I agree with @pranay_stacker; jQuery gives you a simpler way to get the info.

John Weldon
A: 

To continue from John's answer, you may be looking for something like this, if I understand that you want to count the div and input children within the id="maindiv" element:

var maindiv = document.getElementById('maindiv');

var count = maindiv.getElementsByTagName('div').length +
            maindiv.getElementsByTagName('input').length;
Daniel Vassallo
this is ok bcoz its static how to get this dynamically...
rajesh
@rajesh: What do you want dynamic exactly?
Daniel Vassallo
actually currently i am working on remote mapping in which my first activated cursor will be at home, now if i clicked on right arrow of remote then it must go to next tab (suppose services) Hence i am thinking that i must collect no of divs present in page ,then if i pressed right arrow he must know that my next div is this one and inside that i must focus on the first element(may be div input etc) .Please give response asap.Thanks
rajesh
@rajesh: I think you may want to consider posting another question on this issue, maybe providing some examples.
Daniel Vassallo