Reputation: 1523
My HTML is as follows:
<div class="row side cards-row-1 cards-row">
<a href="#" class="card cards-front"> Text </a>
</div>
<div class="row side cards-row-2 cards-row">
<a href="#" class="card cards-front"> Text </a>
</div>
<div class="row side cards-row-3 cards-row">
<a href="#" class="card cards-front"> Text </a>
</div>
I need to get the number value of cards-row when the user clicks on a link.
I thought the best way to do this would be to use the Jquery parent selector and wildcard selector.
This is my Jquery code:
(function($) {
$(document).ready(function() {
"use strict";
$('.cards-front').click(function(e) {
e.preventDefault();
$('.cards-row').removeClass('cards-expand');
var classes = $(this).parent().attr("[class^=card-row-]");
alert(classes);
$(this).parent().addClass('cards-expand');
$(this).insertAfter('<div class="cards-shadow"></div>');
});
$('.cards-back .close').click(function() {
$('.cards-row').removeClass('cards-expand');
$('.cards-shadow').remove();
});
});
})(jQuery);
I am using alert classes
to check what number has been captured.
However, instead of capturing a value it just says undefined
I am not sure what I am doing wrong and would appreciate any pointers. Thanks!
Upvotes: 0
Views: 963
Reputation: 14827
Your selector is wrong, if you want to retrieve the class name, you need to do:
var classes = $(this).parent().attr("class");
If you just want to get the number after cards-row-
and not letter then you can use this regex:
var classes = $(this).parent().attr("class").match(/cards-row-(\d+)/);
But actually, you can use index() in this case:
var classes = $(this).parent().index() + 1;
Since index()
value is 0-based so that you need to increase it by 1 to get the correct value
Upvotes: 2
Reputation: 10994
An easier way would be to strip the letters and leave only the number
var classes = $(this).parent().attr('class').match(/\d+/g);
Upvotes: 0