Pages

27 Apr 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 

Javascript : get all the object where id is like log_XXXX

Easy with jQuery

$("*[id\^='log\_']")
 
Otherwise...
var matches = [];
var elems = document.getElementsByTagName("*");
for (var i=0; i<elems.length; i++) {
  if (elems[i].id.indexOf("log_") == 0)
    matches.push(elems[i]);
}
//matches now is an array of all matching elements.
 
 

Ok, here's a straight JavaScript answer:
 
/ a handy function to aid in filtering:
// takes an array and a function, returns another array containing
// only those elements for which f() returns true
function filter(a, f) 
{ 
  var ret = []; 
  for (var i=0; i<a.length; ++i) 
  {
    if ( f(a[i]) ) 
      ret.push(a[i]); 
  }
  return ret;
}

// this collects all elements in the current document
var elements = document.getElementsByTagName("*");

// and this filters out all but those that match our pattern
var logElements = filter(elements, function(el) 
  { return /log_/.test(el.id) } ); // simple expression