Tom Tucker
Tom Tucker

Reputation: 11916

jQuery selection by pattern

I have a table of form elements where each row represents a record and column represents a field. I need to select all form elements in a given column.

Form elements in the same column have the same name format. For example, form elements that represent a location would have a name in the format record*.location, where * is an index.

Is it possible to select them with a single jQuery selection? If so, how does it compare to doing document.getElementById() on each one of them in a loop, performance wise?

Upvotes: 2

Views: 659

Answers (2)

user113716
user113716

Reputation: 322572

var locations = $('td :input[name$="\\.location"]')

This uses the attribute-ends-with-selector(docs) and will select all elements that end with .location.


Ultimately if you're concerned about performance, you can do your own selection like this:

function selectInputs( el, type ) {
    var arr = [],
        inputs = document.getElementById( el ).getElementsByTagName( 'input' ),
        len = inputs.length;
    while( len-- ) {
        if( inputs[len].name.indexOf( type ) > -1 ) {
            arr.push( inputs[len] );
        }
    }
    return arr;
}

var locations = selectInputs( 'myTable', '.location' );

You could cache away the DOM selection if elements are not added dynamically. You may want to do that whether or not you use jQuery.

Upvotes: 4

JAAulde
JAAulde

Reputation: 19560

Use jQuery's custom selector creation, $.expr. I have an example for you at http://jsfiddle.net/ygSAy/

You'll want to limit use of it to specific contexts unless you really work to make the filter function super efficient.

Edit: a commented and slightly better performant version: http://jsfiddle.net/ygSAy/2/

Upvotes: 4

Related Questions