How would I implement getElementByRegExp?

Hi,

I want to get all elements on the page that have a certain string in their id, in this case “ac_history_3”.

I wrote a small function to do this, which gets all the elements on a page, and then compares them to a reg exp. This works and does what I want.

var myArray = document.getElementsByTagName ('*');
reg = "ac_history_3";
for (var i=myArray.length-1; i>=0; --i){
  if (myArray[i].id.match(reg)){
    alert("This is one of the elements you're looking for");
  }
}

However the form I am working with is really long and I was wondering if there is a more efficient way to do this.

Something like: document.getElementByRegExp(“ac_history_3”);

I would be grateful if someone could tell me if there is a more efficient way to do this, or if the code above is the only way to do what I want.

Cheers.

Yeah, good point.
Thanks very much for that. I have incorporated it into my code.

Instead of getting all the page’s elements, you could speed things up a bit by getting just the form’s elements as in this demo.

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
 
window.onload=function() {
     var formElems = document.getElementById("myForm").elements;
    for(var i=0; i < formElems.length; i++) {
            alert(formElems[i].name);
    } 
}
</script>
</head>
<body>
<form id="myForm" >
 
<div>

      <input type="text" name="txtInp1" />
      <input type="text" name="txtInp2" />
      <input type="checkbox" name="chk1" value="val_1" />

</div>
</form>
</body>
</html>