views:

115

answers:

5

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?

A: 

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);
});
yoavf
i believe the correct syntax in 1.3.1 is $(li[id^=comment])
mkoryak
Don’t forget the quotes.
Gumbo
Or you could just use -> $("li[id^='comment']").get() // Gets an array of elements..
J-P
JimmyP - wasn't aware of that! thanks.
yoavf
A: 

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.

mkoryak
A: 

jquery is definitely a good way to go.

Check out the attribute filters at jquery.com

Rog
A: 

Selectors API runs.

document.querySelectorAll("input[id*='yoursubstring']")

Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.

+1  A: 

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';
});
J-P