Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID via class name

I have this element:

<div class="item item-id-123"></div>

I want to put the ID in a variable via the class name item-id-123.

So I target the element via .item:

$( document ).on( 'click', '.item', function() {
    // get the ID via class name
});

Maybe I can use .match() to get the class name, and then strip item-id- from it so we have 123 left...? What's the appropriate approach here?

like image 302
Henrik Petterson Avatar asked Jan 02 '23 14:01

Henrik Petterson


1 Answers

If you're not sure about the position of your class in the attribute, you can use the RegEx item-id-(\d+)

$(document).on('click', '.item', function() {
  console.log(/item-id-(\d+)/.exec($(this).attr('class'))[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123">Click me</div>
like image 76
Zenoo Avatar answered Jan 05 '23 17:01

Zenoo