Get part of element ID I am getting the number part of the container ID that the button is in. Now I am wondering if I need to create an array using split and then put this number in a variable, or if there is a more efficient way to get it.

.match() also returns an array, so this is almost the same as using split.

I mean the code works and it's ok, but I'm curious to see if there is a better way.



 $('.add').on('click', function(e) {
   e.preventDefault();
   var $this = $(this);
   var tab_number_array = $this.parents('.tab_content').attr('id').split('_');
   var tab_number = tab_number_array[1];
   alert(tab_number);
 });
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt;
&lt;div class="container"&gt;
  &lt;div id="tab_1" class="tab_content"&gt;
    &lt;div class="container"&gt;
      &lt;button class="add"&gt;Add&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="tab_2" class="tab_content"&gt;
    &lt;div class="container"&gt;
      &lt;button class="add"&gt;Add&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="tab_3" class="tab_content"&gt;
    &lt;div class="container"&gt;
      &lt;button class="add"&gt;Add&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
The parents method will traverse the DOM all the way up the chain. Rather use the closest method, which will stop at the first match:

$('.add').on('click', function(e) {
    e.preventDefault();

    var number = $(this).closest('.tab_content').attr('id').split('_')[1];

    alert(number);
});