Forum Moderators: open
I am looking for a way to get multiple elements by there given id.
Like i have something looking like this:
<div id="myDivIdStarts40">Starts 40</div>
<div id="myDivIdStarts20">Starts 20</div>
Now i want to do something like getMultipleElementsById('myDivIdStarts*').
Is there a function that can do this already?
If not, does someone knows of a script that can do this?
Thx in advance
In any case, you could do this using the Yahoo UI Library.
<script type="text/javascript" src="yahoo-min.js"></script>
<script type="text/javascript" src="dom-min.js"></script>
<script type="text/javascript">
function myFunc(el) {
if( el.hasAttribute('id') )
{
return el.id.match( /^myDivIdStarts/ );
}
return false;
}
var els = YAHOO.util.Dom.getElementsBy( myFunc, 'div' );
</script>
Note, I'm not exactly sure on the syntax of the regexpr. Alternatively, you could do something like:
return el.id.substr(0,13) == 'myDivIdStarts';
Where 13 is the length of the string you're comparing it to.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
// <![CDATA[
function GetElementsByPrefix(inPrefix,inRoot){
var elem_array = new Array;
if(typeof inRoot.firstChild!= 'undefined'){
var elem = inRoot.firstChild;
while (elem!= null){
if(typeof elem.firstChild!= 'undefined'){
elem_array = elem_array.concat(GetElementsByPrefix(inPrefix,elem));
}
if(typeof elem.id!= 'undefined'){
var reg = new RegExp ( '^'+inPrefix+'.*' );
if(elem.id.match(reg)){
elem_array.push(elem);
}
}
elem = elem.nextSibling;
}
}
return elem_array;
}function DisplayElements(in_elem_array){
if(in_elem_array.length){
for(var c=0; c<in_elem_array.length; c++){
alert(in_elem_array[c].id);
}
}
}
// ]]>
</script>
</head>
<body>
<div>
<div id="prefix1"></div>
<div id="prefix2"></div>
<div id="prefix3"></div>
<div id="noprefix1"></div>
</div>
<script type="text/javascript">
// <![CDATA[
DisplayElements(GetElementsByPrefix('prefix',document.documentElement));
// ]]>
</script>
</body>
</html>