Guessed
Guessed

Reputation: 427

Extracting A Particular Class With JavaScript or jQuery

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);

Upvotes: 2

Views: 613

Answers (3)

guest271314
guest271314

Reputation: 1

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>

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

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>

Upvotes: 3

user786
user786

Reputation: 4364

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>

Upvotes: 0

Related Questions