Reputation: 339
I have a few divs with class name denoting steps:
<div class="steps jsStep1 circle">Step 1</div>
<div class="steps jsStep2 circle">Step 2</div>
<div class="steps jsStep3 circle">Step 3</div>
My js is wired up like this:
$(document).on("click", ".steps", function () {
var selectedStep = $(this).attr('class').match('["jsStep"]')
});
What I am trying to achieve is get full class name eg "jsStep3" if that div was clicked. What I am getting is ["s"]. Any suggestions would be appreciated.
Upvotes: 3
Views: 1310
Reputation: 115212
The reason that you have getting ["s"]
because the string '["jsStep"]'
would get converted to regex /["jsStep"]/
and the first match would be s
in all case.
To make it work provide a RegExp
object as an argument of String#match
method.
$(document).on("click", ".steps", function() {
var selectedStep = $(this).attr('class').match(/jsStep\d+/)[0];
console.log(selectedStep);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="steps jsStep1 circle">Step 1</div>
<div class="steps jsStep2 circle">Step 2</div>
<div class="steps jsStep3 circle">Step 3</div>
But a better way would be using custom data-*
attribute which can easily get by using data()
method.
$(document).on("click", ".steps", function() {
var selectedStep = $(this).data('step');
console.log(selectedStep);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-step="jsStep1" class="steps circle">Step 1</div>
<div data-step="jsStep2" class="steps circle">Step 2</div>
<div data-step="jsStep3" class="steps circle">Step 3</div>
Upvotes: 3