tags:

views:

84

answers:

2

Suppose you have some <div>s:

<div id="div_num1"></div>
<div id="div_num2"></div>
<div id="div_num3"></div>

You can select all those divs by choosing $("div[id^='div_num']"). How can you buld a function that references the number succeeding the prefix?

For example, a function which will alert the number 3 for "div_num3".

More generally, how can you use full-blown regex in jQuery selectors?

+1  A: 

It should be something like this:

$('div[id^=div_num]').click(function() {
    var m = /div_num(\d+)/.exec($(this).attr('id'));
    if (m == null) // no match
        return;
    alert(m[1]);  // note that the match will be in m[1], not m[0]
}
Alex - Aotea Studios
+2  A: 

If you have the set of elements, you can iterate it and get the number there:

$("div[id^='div_num']").each(function() {
    if (this.id.match(/^div_num(\d+)$/)) {
        alert(RegExp.$1);
    }
})
Gumbo
Thanks, is there no elegant way to do this?
Yuval A
@Yuval A: that *is* the elegant way. You cannot use regexes in jQuery selectors.
Andy E
@Yuval A: If you mean elegant way like a selector that is not just used to describe elements properties to select them (that’s what the selector is for). Then no.
Gumbo
@Gumbo - fair enough, thanks!
Yuval A