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="vrow[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;
}
...
Use the document. querySelectorAll() method to get all elements whose id starts with a specific string, e.g. document. querySelectorAll('[id^="box"]') . The method returns a NodeList containing all the elements that match the provided selector.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
[]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With