Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Get all elements with id id[x]

Tags:

javascript

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;
    }
...
like image 552
abel Avatar asked Sep 15 '10 12:09

abel


People also ask

How do I get all elements with specific id?

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.

Can I get multiple elements by id JavaScript?

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.

How will you retrieve an element with the id?

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.


1 Answers

[] 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.

like image 124
Andy E Avatar answered Sep 30 '22 16:09

Andy E