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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With