3

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.

2
  • Use data for data, ie <div class='steps' data-step='jsStep1' ..> then $(this).data("step") Commented Oct 12, 2016 at 8:53
  • Thanx for this alternative Commented Oct 12, 2016 at 9:20

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.