Pages

Friday 26 April 2013

Javascript, Jquery : How to get all elements which name starts with some string?


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) {
eles
.push(inputs[i]);
}
}
 
 
 
You can use getElementsByName("input") to get a collection of all the 
inputs on the page. Then loop through the collection, checking the name
on the way. Something like this:

 <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>

</head>
<body>

<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>

<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x=0;x<=inputs.length;x++){
myname
= inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert
(myname);
// do more stuff here
}
}
</script>
</body>
</html>
 
Demo 

No comments:

Post a Comment