MintfreshLindfield
MintfreshLindfield

Reputation: 55

Get number from class name and use it in variable

I have a set of links with a number of class names and one of them has a number attached which I'm trying to grab but it doesn't seem to be working...

The links are like this

<div class="et_pb_module et_pb_text et_pb_text_0  et_pb_text_align_left et_pb_bg_layout_light">
  <div class="et_pb_text_inner"><p>Title 1</p></div>
</div>

And the images are like this

<section class="et_pb_module et_pb_fullwidth_header et_pb_fullwidth_header_2 et_pb_text_align_left et_pb_bg_layout_dark et_pb_fullscreen">
    <div class="et_pb_fullwidth_header_container left">
    </div>
</section>

And the jQuery I've tried

jQuery('.et_pb_text').click(function (){
var num = jQuery(this).closest('[class^=et_pb_text_]').attr("class").match(/\d+/)[0];
alert(num);

Temp page can be found here - https://jordan.mintfresh.net/home-2/

Any help much appreciated, thanks!

Upvotes: 0

Views: 64

Answers (1)

I believe that your code should look like:

$('.et_pb_text').click(function() {
  var num = jQuery(this).attr("class").match(/\d+/)[0];
  alert(num);
});

et_pb_module et_pb_text et_pb_text_0  et_pb_text_align_left et_pb_bg_layout_light
                 ^           ^
Clicked class ---            |
Element your check for ------

You are trying to use .closest() to find a class one the same element.

Demo

$('.et_pb_text').click(function() {
  var num = jQuery(this).attr("class").match(/\d+/)[0];
  alert(num);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et_pb_module et_pb_text et_pb_text_0  et_pb_text_align_left et_pb_bg_layout_light">
  <div class="et_pb_text_inner">
    <p>Title 1</p>
  </div>
</div>
<section class="et_pb_module et_pb_fullwidth_header et_pb_fullwidth_header_2 et_pb_text_align_left et_pb_bg_layout_dark et_pb_fullscreen">
  <div class="et_pb_fullwidth_header_container left">
  </div>
</section>



<div class="et_pb_module et_pb_text et_pb_text_3  et_pb_text_align_left et_pb_bg_layout_light">
  <div class="et_pb_text_inner">
    <p>Title 3 </p>
  </div>
</div>
<section class="et_pb_module et_pb_fullwidth_header et_pb_fullwidth_header_2 et_pb_text_align_left et_pb_bg_layout_dark et_pb_fullscreen">
  <div class="et_pb_fullwidth_header_container left">
  </div>
</section>

Upvotes: 1

Related Questions