Richie Lai
Richie Lai

Reputation: 502

JQuery: Attribute selector doesn't work as expected

Given the following code, I would expect an alert of "searchRes1" which is a direct match of the id, and for the second block, i would expect it to alert the other two div's as well since id contains "search". What am i missing?

            <div id="sRes">
               <h4>Search for things</h4> 
                <div id="searchRes1">123</div>
                <div id="searchRes2">456</div>
                <div id="searchRes3">789</div>
            </div>
            <script>
                $("#sRes div[id='searchRes1']").each(function () {
                    alert($(this).attr("id"));
                });

                $("#sRes div[id~='search']").each(function() {
                    alert($(this).attr("id"));
                });
            </script>

Upvotes: 1

Views: 1130

Answers (3)

Jishnu A P
Jishnu A P

Reputation: 14382

the first one is working fine for me http://jsfiddle.net/raW26/

And for the second one to work i think the attribute that you're selecting must be delimited by spaces

You must use *= or ^= for it to work

P.S. you don't need to use $(this).attr("id") just this.id is enough

$("#sRes div[id='searchRes1']").each(function () {
            alert($(this).attr("id"));
        });

        $("#sRes div[id*='search']").each(function() {
            alert($(this).attr("id"));
        });

Upvotes: 1

Xr.
Xr.

Reputation: 1410

In CSS selectors, contains (~=) means contains the full word. This can be useful for things like rel="foo bar" which would be matched by rel~='foo', rel~='bar' but not rel~='fo'.

Try with startsWith (^=):

$("#sRes div[id^='search']")

http://www.w3.org/TR/css3-selectors/#attribute-selectors

Upvotes: 2

xkeshav
xkeshav

Reputation: 54016

u miss the name and also use ! not ~

$("#sRes div[id!='searchRes1']").each(function() {
                    alert($(this).attr("id"));
                });

DEMO

Reference

Upvotes: 0

Related Questions