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.
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>
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