PDA

View Full Version : Getting multiple ID items from the page.



jsnewbie
02-24-2009, 11:51 AM
Hi there,

I am trying to find a javascript code using which I can access multiple elements through their ID. I know it has to be using document.getElementByID and using loops...

Thanks a lot for the help

codeexploiter
02-24-2009, 11:56 AM
Here is one function. Use it instead of using document.getElementById in whereever you need it.


function get(el) {
if (el) {
if (typeof el === ’string’) {
return document.getElementById(el);
}
if (typeof el === ‘object’ && el.length && el.length > 0) {
var els = [];
for (var i = 0; i < el.length; ++i) {
el[i].nodeType !== undefined ? els.push(el[i]) : els.push(document.getElementById(el[i]));
}
return els;
}
if (typeof el === ‘object’ && el.nodeType !== undefined) {
return el;
}
}
}


Usage


var el = get(’myid’); //For retrieving single element, returns the element itself if it found.
var els = get(['myid1','myid2']);//For retrieving multiple elements, returns an array.

Please let me know if you need any assistance with the usage.

Hope this helps.

jsnewbie
02-24-2009, 12:18 PM
I'll try this and let you know about the issues, if any.