Thursday, March 31, 2011

Getting elements using Javascript

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?

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

0 comments:

Post a Comment