Using javascript how do I get the number of elements present with the id of id[x]?
Sample HTML:
<input name="vrow[0]" id="vrow[0]" value="0" type="text"/>
<input name="v开发者_高级运维row[1]" id="vrow[1]" value="0" type="text"/>
<input name="vrow[2]" id="vrow[2]" value="0" type="text"/>
<input name="vrow[3]" id="vrow[3]" value="0" type="text"/>
The above html is generated depending on user input. How do I detect how many elements are present using javascript?
Currently I can detect presence of an element like this
Sample Javascript
if(document.getElementById('vrow[0]')){
var row=0;
}
if(document.getElementById('vrow[1]')){
row=1;
}
...
[]
are not valid characters in ID attributes in HTML4.01. Even in HTML5, however, you should use the name attribute (without the numeric indexes), and then use getElementsByName():
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
var vrows = document.getElementsByName("vrow");
alert(vrows.length);
Note that older versions of IE and Opera may return elements with id
attributes that have the same value as the name specified in getElementsByName(). IE may also return non-input elements with a name attribute that has the same value.
var inputTags = document.getElementsByTagName('INPUT');
var count=0;
for(var i=0;i<inputTags.length;i++)
if(inputTags[i].id.contains('vrow[')
count++;
If for some reason you want to stick with the names of your input elements you can use:
var inputs = Array.prototype.slice.call(document.getElementsByTagName('input'));
var rows = inputs.filter(function (el) { return el.name.indexOf('vrow[') == 0 });
alert(rows.length);
getElementById always returns one element (since id are unique). getElementsByName can result a list of elements.
<html>
<head>
<script>
function getElements() {
var elements = document.getElementsByName("vrow[]");
alert(elements.length);
}
</script>
</head>
<body onload="getElements()">
<input name="vrow[]" id="vrow_0" value="0" type="text"/>
<input name="vrow[]" id="vrow_1" value="0" type="text"/>
<input name="vrow[]" id="vrow_2" value="0" type="text"/>
<input name="vrow[]" id="vrow_3" value="0" type="text"/>
</body>
</html>
If you use a JavaScript library with a query function supporting CSS3, such as Prototype, you can use the attribute starts-with selector to find id attributes beginning with vrow[
So in Prototype this would be
$$('input[id^=vrow[]').each
NB this is untested, you might have to escape the [ in the selector
Prototype $$ function
精彩评论