Claudio Delgado
Claudio Delgado

Reputation: 2349

Target an ID with jQuery that I only know the beginning to

Is it possible to target IDs that begin with 'category_id_' and after that there are 3 digits. But I want to target all IDs that only begin with 'category_id_'.

Is this possible and if yes, how?

Thanks

Upvotes: 0

Views: 66

Answers (2)

Adil
Adil

Reputation: 148150

Use Attribute Starts With Selector [name^="value"] with wild card

$('[id^=category_id_]');

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string, reference.

To bind event

$(document).on ("click", "[id^=category_id_]", function () { 

Upvotes: 3

adeneo
adeneo

Reputation: 318302

That would be the attribute starts with selector :

$('[id^="category_id_"]')

and to be even more specific you can use a filter:

$('[id^="category_id_"]').filter(function() {
    var str = this.id.replace('category_id_','');

    if(str.length === 3) {
       // there where 3 more characters 

       str.replace(/\D/,'').length === 3 // they where all numbers
    }
}).something();

Upvotes: 3

Related Questions