7

There are several divs on my page with classes my_widget-2, my_widget-8, etc. What JavaScript or jQuery code can I use to get the number "2" (ie. the number that appends the first matching widget)?

Note: If I were to write this question again, I would change the order of these class names and ask for a way to get "8" in order to avoid giving the impression that I want the smaller number.

5
  • Please clarify if you have only one or multiple classes so I can edit my answer to show you how to retrieve the number part. Commented Jan 5, 2010 at 13:46
  • Yes, the divs have other classes (eg. 'widget', 'my_widget') Commented Jan 5, 2010 at 13:50
  • I think you should clarify what exactly you want to have. Is it all DIV elements with the class my_widget-2 (since you wrote “get the number 2”) or do you want to have all DIV elements with a class of the form my_widget-N? Commented Jan 5, 2010 at 14:09
  • I want to get the number "2" only. Just the number. Next, I will use the number to style another div's background image. Commented Jan 5, 2010 at 14:22
  • Responses so far could have been useful for a bigger number of users as they don't answer a too specific need like mine. And they will be lost when (if) you make changes to your codes :( Commented Jan 5, 2010 at 14:46

5 Answers 5

10
$( "[class*='my_widget']" ).each ( function () {
    var elClasses = $( this ).attr ( 'class' ).split ( ' ' );

    for ( var index in elClasses ) {
        if ( elClasses[index].match ( /^my_widget-\d+$/ ) ) {
            var classNum = elClasses[index].split ( '-' )[1];
            alert ( classNum );
            break;
        }
    }
} );

Use the "attributeContains" selector to get all elements that have a class my_widget-*, and then loop trough all the classes the element has searching for you class. Once you find it, extract the number part.

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

8 Comments

What if the element has multple classes? The startswith wouldn't work for them.
Make it "[class*='my_widget']" and it should work in the case of multiple classes.
@ryanulit: hehe, was adding that, didn't see your comment :)
What about class names just containing my_widget like not_my_widget?
It now only matches classes in the form "my_widget-NUM"
|
1

This should do the trick:

$("[class^='my_widget']").each(function() {
    var classParts = $(this).attr('class').split('-');
    var number = classParts.pop();
});

Please note that it will only work if there is a singular class, otherwise you'd get something like 8 otherclass as a result.

1 Comment

Another tricky part here is that I only want the first number suffix ('2'), not the others... not actually sure if jQuery is the right tool to approach this. This whole thing really is part of a Wordpress situation but I wasn't able to add my original question that had a link to this one. (noob -> need to wait another 10 mins. or so)
1

Basic JS approach:

<div id="x" class="widget-2 lang-日本語">foo</div>

function Element_getClassArgument(el, name) {
    var classes= el.className.split(' ');
    var prefix= name+'-';
    for (var i= classes.length; i-->0;)
        if (classes[i].substring(0, prefix.length)==prefix)
            return classes[i].substring(prefix.length);
    return null;
}

Element_getClassArgument(document.getElementById('x'), 'widget'); // 2

If you wanted to include whitespace characters, or a hyphen in a name, you'd have to introduce an encoding scheme of some sort, for example encodeURIComponent. But often you can get away without that.

Wrapping in something with $ in the name is left as an exercise for the reader. :-)

Comments

0

If you want to get the DIV elements with a class my_widget-2, use this selector:

$("div.my_widget-2")

But if you want to get all DIV elements with a class of the form my_widget-N where N is an arbitrary number, try this:

$("div[class]").each(function() {
    var matches = this.className.match(/(?:^|\s+)my_widget-(\d+)(?:\s+|$)/g);
    if (matches !== null) {
        alert(matches);
    }
})

6 Comments

I downvoted your original answer that didn't make any sense. Now I can't undo :\
@Jan Hančič: And why didn’t it make any sense? He just asked how to get the “number 2” of some DIV elements with classes like my_widget-2 and my_widget-8. If “number 2” refers to the DIV elements with the class my_widget-2 my previous answer makes perfect sense.
No, he wants to get elements that have a class like my_widget-AND SOME NUMBER. And originally you had the wrong selector even for that what you are saying :)
@Jan Hančič: And where did he say that?
I think it's clear from his question. Why would he need to get "2" if he already knew the full class name "my_widget-2"?
|
0

Try element.attr('class').match(/my_widget-(\d+)/)[1]

It should return the column number as a string so just run parseInt() on it

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.