jQuery Wildcard Selector Syntax

An application I'm working on at the moment had the need for me to select a group of elements (in this case they're divs) which all contained a common string in their id (in my case, the prefix for the div's id was 'content', so 'contentOne', 'contentTwo', etc).

I found a lot of people saying they way to go was to use \\S* as shown in sample One below, however I couldn't get it to work no matter how many variations I tried. I found a few other people who'd had the same problem as me – reassuring, but I'd quite like to know what we're overlooking. It's no major deal as I found a working alternative (code sample Two below), but I am a little curious as to why a few people might be running into problems using the first piece of sample code.

// One
$('#content\\S*').each(function () { 
    $(this).hide();
});

// Two
$("div[id^='content']").each(function() {
    $(this).hide();
});

Anyone able to shed some light?

Tags:
Posted on Thursday, February 12, 2009 1:38 PM |

Like this? Share it!

  • # re: jQuery Wildcard Selector Syntax
    Gravatar
    Commented on 3/28/2009 3:12 AM

    I've found this example:

    You can use the filter function to apply more complicated regex matching. Here's an example which would just match the first three divs.

    <div id="abcd"></div>
    <div id="abccd"></div>
    <div id="abcccd"></div>
    <div id="abd"></div>

    $('div')
    .filter(function() {
    return this.id.match(/abc+d/);
    })
    .html("Matched!")
    ;

    here:

    stackoverflow.com/.../jquery-selector-regular-e...

    but I'can get it work

  • # re: jQuery Wildcard Selector Syntax
    Gravatar
    Commented on 10/3/2010 11:19 AM

    Thank you for posting this, I couldn't get this to work either.

    // One
    $('#content\\S*').each(function () {
    $(this).hide();
    });

    This worked great for me

    // Two
    $("div[id^='content']").each(function() {
    $(this).hide();
    });

  • # re: jQuery Wildcard Selector Syntax
    Gravatar
    Commented on 10/14/2011 12:07 AM

    I've written a follow up to this post here: rosshawkins.net/.../...s-some-simple-examples.aspx

    The much shorter version for anyone experience the problem I was talking about above, is that support for the first method was dropped in jQuery 1.3.2.

Post a comment
Please add 1 and 8 and type the answer here:
Remember me?
Ensure the word in this box says 'orange':