Misha Moroshko Misha Moroshko - 2 years ago 141
HTML Question

How to get all elements which name starts with some string?

I have an HTML page.

I would like to extract all elements which name starts with "q1_".

How can I achieve this in JavaScript ?

Thanks !

Answer Source

A quick and easy way is to use jQuery and do this:

var $eles = $(":input[name^='q1_']").css("font-color","yellow");

That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:

var DOMeles = $eles.get();

see http://api.jquery.com/attribute-starts-with-selector/

In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:

var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('q1_') == 0) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download