开发者

How to count no of elements?

开发者 https://www.devze.com 2023-01-03 14:26 出处:网络
suppose i have what i want is inside maindiv i want to count no of elements(may be div input tags)present.

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 t开发者_如何学编程hat how to count element.

Thanks


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.


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;
0

精彩评论

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