RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

How do I write a jQuery selector to match two elements whose ids start with the same string

I have 2 loader images, with element ids loader1 and loader2. I bind to the first one with:

$('#loader1')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

How can I bind the same code to loader2 without repeating the whole thing?

Upvotes: 2

Views: 629

Answers (4)

Alexey Lebedev
Alexey Lebedev

Reputation: 12197

$('#loader1, #loader2')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });

See jQuery Multiple Selector documentation.

Upvotes: 4

Dutchie432
Dutchie432

Reputation: 29160

The proper way to do this, in general, would be to give both elements the same class name... This would also make it much easier if you need to handle more than 2 or 3 elements.

<img src="image1.png" class="loader" id="loader1" />
<img src="image2.png" class="loader" id="loader2" />
<img src="image3.png" class="loader" id="completelyDifferentId" />

Then you can easily access them this way

$('.loader').hide().ajaxStart(function() {
    $(this).show();
}).ajaxStop(function() {
    $(this).hide();
});

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074335

You can use an attribute starts with selector (^=):

$("[id^=loader]")
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

If you can also include the tag name, that will help on many browsers, as jQuery's selector engine can use the tag name to narrow down the list of candidates before looking at the id value. E.g., if both are img elements, then:

$("img[id^=loader]")
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

Upvotes: 3

Marek Tuchalski
Marek Tuchalski

Reputation: 489

This should help you:

$('div[id^=loader]')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })

I used div, but you can use every html tag for this: p, span, b etc.

You have to use ^= selector, where ^= means starts with. More information can be found here: http://api.jquery.com/attribute-starts-with-selector/. All selectors are listed here: http://api.jquery.com/category/selectors/

Upvotes: 4

Related Questions