I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
See Question&Answers more detail:osI have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
See Question&Answers more detail:osA quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("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) {
eles.push(inputs[i]);
}
}