frogg3862
frogg3862

Reputation: 491

Get class containing string and number from multiple classes

I have the image below with multiple classes. On click, I need to get the string "wp-image-1228" (those four numbers will always be different) from all of the classes.

I've got the click down, but I can't seem to get what I need using .match.

<img class="size-post_gal wp-image-1228 aligncenter">

Upvotes: 3

Views: 2426

Answers (2)

Brad
Brad

Reputation: 6332

$("img[class^='wp-image-']") is a valid selector. that what you're looking for?

Also, here's a working fiddle to get the actual string: http://jsfiddle.net/pFVyE/

$(document).ready(function(){
$('img').filter(function() {
        var classes = $(this).attr('class').split(" ");                                
        for(i = 0; i < classes.length; i++){
            if(classes[i].match(/^wp-image-/)){
            alert(classes[i]); 
            }
        }    

    }); 
});

Upvotes: 1

Walter Tross
Walter Tross

Reputation: 12624

If you are in the jQuery .click() handler and need that ID that follows wp-image-:

var id = $(this).prop('class').match(/wp-image-([0-9]+)/)[1];

Upvotes: 6

Related Questions