Yuval Adam
Yuval Adam

Reputation: 165232

jQuery wildcard selection

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?

Upvotes: 1

Views: 1546

Answers (2)

Gumbo
Gumbo

Reputation: 655229

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);
    }
})

Upvotes: 5

Alex Korban
Alex Korban

Reputation: 15126

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]
}

Upvotes: 1

Related Questions