1

Say I had the following 4 divs:

<div class="mine-banana"></div>
<div class="mine-grape"></div>
<div class="mine-apple"></div>
<div class="orange"></div>

I've discovered I can use the following JQuery selector to get the 3 "mine" divs, but I can't quite figure out how to return all the fruits that are "mine" :)

$('[class*=" mine-"]').each(function() {
    var fruit = $(this).????
});
3
  • See stackoverflow.com/questions/2400386/get-class-name-using-jquery Commented May 29, 2014 at 16:50
  • 3
    Any reason why you're mixing an identifier ("mine-") with data (the fruit)? Separate them into separate attributes. Give them the class "mine" and target them that way. Then store the fruit associated in an attribute called data-fruit and get that attribute value Commented May 29, 2014 at 16:53
  • 1
    That makes more sense. I'll try it, thanks. Commented May 29, 2014 at 16:54

1 Answer 1

2

DEMO

The best way to accomplish that is to refactor your html, as @Ian pointed it out, for example :

<div class="mine" data-mine-fruit="banana"></div>
<div class="mine" data-mine-fruit="grape"></div>
<div class="mine" data-mine-fruit="apple"></div>
<div class="orange"></div>

The JS code is straightforward now :

var fruits = $('.mine').map(function () {
    return $(this).attr('data-mine-fruit')
});

If you still want to use your current code, here is a regex-based code

var fruits = []
$('[class*=" mine-"], [class^="mine-"]').each(function() {
    fruits.push( this.className.match(/[^a-z0-9_-]?mine-([0-9a-z_-]+)/i)[1] );

})

which really works

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

Comments

Your Answer

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