tags:

views:

371

answers:

3

I am trying to select elements that do not match a given attribute id. Based on the following simplified example, why does $("td[groupId != 1]") return elements that do not even have the groupId attribute? Is there another way to select elements that have a groupId where the value is not 1?

<table border="1">
<tr>
 <td>Group 1</td>
 <td groupId="1">1 - 1</td>
 <td groupId="1">1 - 2</td>
 <td groupId="1">1 - 3</td>
 <td>2</td>
 <td groupId="2">2 - 1</td>
 <td>3</td>
 <td groupId="3">3 - 1</td>
 <td>Total</td>
</tr>
<tr>
 <td>1</td>
 <td groupId="1">1</td>
 <td groupId="1">1</td>
 <td groupId="1">1</td>
 <td>2</td>
 <td groupId="2">2</td>
 <td>3</td>
 <td groupId="3">3</td>
 <td>0</td>
</tr>
<tr>
 <td>1</td>
 <td groupId="1">1</td>
 <td groupId="1">1</td>
 <td groupId="1">1</td>
 <td>2</td>
 <td groupId="2">2</td>
 <td>3</td>
 <td groupId="3">3</td>
 <td>0</td>
</tr>
</table>
+3  A: 

Try:

$("td[groupId][groupId!='1']")

This type of selector matches all elements with the attribute groupId, but then only chooses the ones where the value is not 1.

John Rasch
+3  A: 

You could do the following, first select all td's with groupId != 1 and then select those who have groupId specified from that jQuery set:

$('td[groupId!= 1]').filter('[groupId]');

IMHO this is perfectly logic, td's that do not have a groupId have a groupId that does not equeal 1, thus are added to the resultset. Or to put it in code:

var x = {};
typeof x.foo === 'undefined'; //true
x.foo !== 1; //true
Pim Jager
+2  A: 

Try $("td[groupId][groupId != 1]")

This will select all td that have a groupId and then select all td in that set that do not have the value 1.

PS. This is documented behaviour of the not operator.

plep
From the docs: Matches elements that either **don't have the specified attribute** or do have the specified attribute but not with a certain value.
altCognito
Thanks for pointing out the docs.
tessa