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

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.