Search code examples
jqueryjquery-selectorseachjquery-eventsmouseenter

jQuery select all element starting with "o" and followed by number


I would like to add event on some div. The object is when a user put his mouse on a div, do something and when his mouse exit my div do some other thing. I would like to add that event on each div with begin with "0" followed by an number directly. But the problem is I can't access to jQuery official doc and I don't find the right way to do that with Google. I think that:

$('div[id^="o"]')

it work but I would like to be sure that it select only the right div and not the other who start with o and aren't followed directly by a number.

To do my event is possible to something like that?

$(the right selector).each(function whenMouseEnter(element,id), function whenMouseExit(element,id));

Solution

  • Because jQuery lacks a regular-expression function for it's selectors, you'll need to use filter() to explicitly test each found element's id:

    $('div[id^="o"]').filter(function () {
        return (/^o\d/).test(this.id);
    }).hover(function () {
        // mouse over
    }, function () {
        // mouse leave
    });
    

    References: