1

Is there a way to call a function when an id matches a regex?

I have an app where I have about 20 or so divs calling the same function by onclick and I'm trying to get rid of the onclicks and just find those divs by id. The divs id's start the same way for instance: sameId_xxx

This is what I have working but I was wondering if I could put the condition in the function call so it's not being called for every div on the page.

$("div").click(function () {
    var id = this.id;
    if (id.match(/sameId_/)) {

    }
}
3
  • Some have different classes. Necessity for the design Commented Sep 13, 2012 at 14:56
  • 1
    Yeah, but you could add another class to them that separates them from the other divs, say mySpecialKindOfDiv. This won't interfere with the CSS. Commented Sep 13, 2012 at 14:58
  • $('div[id^=sameID_]') Commented Sep 13, 2012 at 14:58

4 Answers 4

7
$('div[id^="sameId_"]').click(...)

Demo: http://jsfiddle.net/kpcxu/

For more info, see Attribute Starts With selector.

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

1 Comment

Thanks. Incorporated into answer.
2

Try the jQuery 'attribute contains selector':

$('div[id*="sameId_"]').click(function() {
// Do stuff
});

1 Comment

As per Shawn Chin's answer above the attribute starts selector would be more accurate
0

I think better filter all div with using necessary condition and next add handler.

For example:

$('div')
    .filter(function() { return $(this).attr('id') % 2 })
        .click(function(){alert($(this).attr('id'))});​

Live demo on JSFiddle

Or you can use var id = $(this).attr('id') in your code.

Comments

0

I think the other answers (with filtering on the id up front) are better, but for posterity, here is what you actually asked for:

$("div").click(function () {
    var id = this.id;
    if (id.match(/(sameId_)(.)+/)) {
        console.log("matched");
    }
}​);​

where "sameId_" is a case sensitive representation of what you want to match.

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.