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).????
});
  • See http://stackoverflow.com/questions/2400386/get-class-name-using-jquery – mccainz May 29 '14 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 – Ian May 29 '14 at 16:53
  • 1
    That makes more sense. I'll try it, thanks. –  May 29 '14 at 16:54

1 Answers1

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

Utopik
  • 3,783
  • 1
  • 21
  • 24