I have a bunch of input elements that have a particular substring in their IDs. Using javascript, is there a way to get these elements as an array? I wouldn't know the full ID - only the substring.
Is this any simpler if I use JQuery?
I have a bunch of input elements that have a particular substring in their IDs. Using javascript, is there a way to get these elements as an array? I wouldn't know the full ID - only the substring.
Is this any simpler if I use JQuery?
Quite easy with jQuery. Example:
$("li[id^='comment']")
Select all "li" where id starts with "comment".
EDIT
To get those into an array:
var myArray = new Array;
$("li[id^='comment']").each(function() {
var thisId = $(this).attr("id");
myArray.push(thisId);
});
its simpler if you use jquery, otherwise you will have to start from document body, get its children, parse their ids, select matching elements, and continue down the tree.
jquery is definitely a good way to go.
Check out the attribute filters at jquery.com
Selectors API runs.
document.querySelectorAll("input[id*='yoursubstring']")
Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.
How about a non-jQuery answer...hmmm!?
function getAndFilter(elems, filter) {
var length = elems.length,
ret = [];
while (length--) {
if(filter(elems[length])) {
ret[ret.length] = elems[length];
}
}
return ret;
}
getAndFilter(document.getElementsByTagName('input'), function(input) {
// Your custom logic/rule goes here:
return input.id.substr(0,5) === 'HELLO';
});