Reputation: 7094
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?
Upvotes: 4
Views: 184
Reputation: 18997
This is alternative to @Zenoo's answer, just without the regex.
$(document).on('click', '.item', function() {
console.log($(this).attr('class').split("item-id-")[1].split(" ")[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item something here item-id-123 hHmmMM hey">Click me</div>
Upvotes: 2
Reputation: 33726
Assuming that sample item item-id-123
, you can split the class names and get the number part using a regex.
This approach breaks the loop when a match is found.
$(document).on('click', '.item', function() {
var names = $(this).attr('class').split(/\s+/);
var id;
for (var name of names) {
var aux;
if ((aux = name.replace(/[^\d]+/, '').trim()) !== '') {
id = aux;
break;
}
}
console.log(id);
});
<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>
Or, even simpler, get the captured group related to id-number
:
$(document).on('click', '.item', function() {
var id = $(this).attr('class').match(/id-(\d+)/).pop();
console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123 another-class-567">Click me!</div>
Upvotes: 2
Reputation: 7004
If your structure is always:
<div class="item item-id-123"></div>
Then you can try this if you won't regex:
$( '.item' ).on( 'click', function() {
// get the ID via class name
var id = $(this).attr('class').split('item-id-')[1];
$('#result').text(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="item item-id-123">click me</span>
<div id="result"></div>
Upvotes: 1
Reputation: 4370
ID with numbers as in your example
$( document ).on( 'click', '.item', function() {
console.log($(this).attr("class").match(/\d+/)[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123">click</div>
Upvotes: -2
Reputation: 12880
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>
Upvotes: 6