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>
In CSS selectors, contains (
~=) means contains the full word. This can be useful for things likerel="foo bar"which would be matched byrel~='foo',rel~='bar'but notrel~='fo'.Try with startsWith (
^=):http://www.w3.org/TR/css3-selectors/#attribute-selectors