2

I have some lments, like this:

<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>

I can select them using:

lments = $('[class^="item"]');

But how do I get the "45", "46", and "47"?

I'm starting with something like this:

itsClass = lments[i].getAttribute('class');

I don't know where to go from here, but want to end up with the equivalent of this:

lmentsItemNum = someExtractorFunction(itsClass);
Guessed
  • 417
  • 1
  • 4
  • 15
  • possible duplicate of [Get class name using jQuery](http://stackoverflow.com/questions/2400386/get-class-name-using-jquery) – Ozan Sep 16 '15 at 02:31

3 Answers3

3

Since you need to get the class name at the beginning you can do something like this using map()

  1. Use map() to iterate over jQuery object
  2. Extract digits from class name using split() and return
  3. For getting the result array use get()

lments = $('[class^="item"]').map(function() {
  return this.className.split(' ')[0].split('-')[1];
}).get();
console.log(lments);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>

If not in this format then

lments = $('[class*="item-"]').map(function() {
  var a;
  this.className.split(' ').forEach(function(v){
  if(v.match(/^item-\d+$/))
    a=v.split('-')[1];
  }); 
  if(a)
  return a;
}).get();
console.log(lments);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-big top grid"></lment>
<lment class="item-47 big top stop"></lment>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

try this

$(document).ready(function() {

  $.each($("lment"), function(a, e) {
    alert($(e).attr("class").split('-')[1].split(' ')[0]);

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>
user786
  • 3,902
  • 4
  • 40
  • 72
0

Try creating array , utilizing String.prototype.match() with RegExp argument /\d+/ to return digit within Element.className as item within array

var lments = document.querySelectorAll("[class^=item]");

function someExtractorFunction(items) {
  var arr = [];
  for (var i = 0; i < items.length; i++)
    arr.push(items[i].className.match(/\d+/)[0])
  return arr
}

var lmentsItemNum = someExtractorFunction(lments);

console.log(lmentsItemNum)
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>
guest271314
  • 1
  • 15
  • 104
  • 177