Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Return class name based on partial string

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.

like image 201
Breaker Avatar asked Apr 19 '26 17:04

Breaker


1 Answers

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>
like image 185
Pranav C Balan Avatar answered Apr 23 '26 10:04

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!