I want to put the identifier in a variable through...">

Get identifier via class name

I have this element:

<div class="item item-id-123"></div>

I want to put the identifier in a variable through the class name item-id-123.

So, I am aiming the element at .item:

$( document ).on( 'click', '.item', function() {
    // get the ID via class name
});

Maybe I can use .match()to get the name of the class, and then remove from it item-id-so that we have left 123...? What is the approach here?

+4
source share
5 answers

If you are not sure about your position classin the attribute, you can use RegExitem-id-(\d+)

$(document).on('click', '.item', function() {
  console.log(/item-id-(\d+)/.exec($(this).attr('class'))[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123">Click me</div>
Run codeHide result
+6
source

Assuming a pattern item item-id-123, you can split the class names and get the number with a regular expression.

This approach breaks the loop when a match is found.

$(document).on('click', '.item', function() {
  var names = $(this).attr('class').split(/\s+/);
  var id;
  for (var name of names) {
    var aux;
    if ((aux = name.replace(/[^\d]+/, '').trim()) !== '') {
      id = aux;
      break;
    }
  }
  console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123">Click me!</div>
Run codeHide result

, , , id-number:

$(document).on('click', '.item', function() {
  var id = $(this).attr('class').match(/id-(\d+)/).pop();
  console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123 another-class-567">Click me!</div>
Hide result
+2

@Zenoo, .

$(document).on('click', '.item', function() {
  console.log($(this).attr('class').split("item-id-")[1].split(" ")[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item something here item-id-123 hHmmMM hey">Click me</div>
Hide result
+2

:

<div class="item item-id-123"></div>

Then you can try this if you are not a regular expression:

$( '.item' ).on( 'click', function() {
   // get the ID via class name
   var id = $(this).attr('class').split('item-id-')[1];
   $('#result').text(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="item item-id-123">click me</span>
<div id="result"></div>
Run codeHide result
+1
source

ID with numbers, as in your example

$( document ).on( 'click', '.item', function() {
    console.log($(this).attr("class").match(/\d+/)[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item item-id-123">click</div>
Run codeHide result
-2
source

Source: https://habr.com/ru/post/1695354/


All Articles