Reputation:
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?
Upvotes: 1
Views: 168
Reputation: 111870
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';
});
Upvotes: 1
Reputation:
Selectors API runs.
document.querySelectorAll("input[id*='yoursubstring']")
Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.
Upvotes: 0
Reputation: 4085
jquery is definitely a good way to go.
Check out the attribute filters at jquery.com
Upvotes: 0
Reputation: 57918
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.
Upvotes: 0
Reputation: 21213
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);
});
Upvotes: 0