1

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?

1
  • Nearly everything in javascript is simpler using JQuery
    – seanb
    Feb 12, 2009 at 23:16

5 Answers 5

1

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

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);
});
1
  • 1
    Or you could just use -> $("li[id^='comment']").get() // Gets an array of elements..
    – James
    Feb 12, 2009 at 23:17
0

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.

0

jquery is definitely a good way to go.

Check out the attribute filters at jquery.com

0

Selectors API runs.

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.