views:

853

answers:

2

Hey.

I'm having a unknown number of elements like so:

<div class="item item-1"></div>
<div class="item item-2"></div>
<div class="item item-3"></div>

What I want to do, is check if each item has a classname starting with "item-". If true, then extract the id. Something like this:

$("container").each(function
    if ($(this).hasClassNameStartingWith("item-"))
        console.debug(theId);
);

How is this possible?

Thanks in advance!

+1  A: 

Use the contains selector on the class attribute:

$('container[class*=" item-"]').each( function() {
    var classID = null;
    var classes = $(this).attr('class').split( ' ' );
    for (var i = 0, len < classes.length; i < len; ++i) {
        var class = classes[i];
        if (class.match( /^item-/ )) {
            classID = class.replace("item-",'');
            break;
        }
    }
    if (classID) {
        ... do something ...
    }
});

Note the use of quotes to include the space, given your sample mark up. You could also omit the space if the "item-N" class could appear at the beginning of the list and you were sure that there weren't any classes that would accidentally match that string.

Updated example to show how to extract identifier portion of class name.

tvanfosson
Yes! Why didn't I think of that. But how would I get the ID?
Kordonme
$(this).attr('id')
David Liddle
David: The id in the "item-N" class.
Kordonme
Go through the classes and find the one that matches the pattern. Extract the number by removing the leading "item-". I'll update.
tvanfosson
A: 

You can perform a regular expression match on the child elements' class attribute:

var itemIDRe = /(?:^|[ \t\n\r\f\u200b]+)item-([^ \t\n\r\f\u200b]+)/;

$('#container').children().each(function() {
  var match = itemIDRe.exec($(this).attr('class'));
  var itemID = match ? match[1] : null;

  // Do something with itemID.
});

The regular expression is based on the HTML 4 definition for the class attribute and white space.

Annabelle