user1555112
user1555112

Reputation: 1987

How to get the class name by a substring?

I have a link with classes like this:

<a class="btn red relevant participant-1 training_id-1 state-1" href="#">

I need to read the 'id' numbers for a later action with ajax posts. How can I catch from class 'participant-1' the number '1'?

I tried with

var classList = $(this).attr('class').split(/\s+/);

but my class names will have a different order from time to time. Therefore I would need to catch them by part of their names.

Does anyone has an idea how to do that?

Upvotes: 1

Views: 753

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

I suggest to use data-* attributes instead.

So first set the data-id attribute like :

$('selector').data('id','value');

The HTML so will looks like :

<a class="btn red relevant participant state" data-id='1' href="#">

Then in your js just use the jQuery method .data() :

var id = $(this).data('id');

Hope this help.

Upvotes: 3

Related Questions