The above yellow link does not provide a solutions to this. The correct answer is .siblings()
which is not in any of the linked solutions
I am trying to select all td
elements except for the one passed as $(this)
. What is the proper way to do this ?
I don't think the following works :
$(this).find(':not')
..since I am looking for all at the same DOM level as $(this).
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function() {
alert($(this).text());
});
});
</script>
</head>
<body>
<a>Apples</a><br />
<a>Bananas</a><br />
<a>Oranges</a><br />
</body>
</html>
Just stating this to be clear that I am looking for a general solution, not one specific to this example. :)
答案 0 :(得分:4)
Use the .not()
method to exclude a previous jQuery selection. You can pass a selector to it, but also an existing element or jQuery object.
var others = $('td').not(this);
$('td').on('click', function() {
$(this).css('color', 'red')
$('td').not(this).css('color', 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>Cell1</td><td>Cell2</td></tr>
<tr><td>Cell3</td><td>Cell4</td></tr>
<tr><td>Cell5</td><td>Cell5</td></tr>
</table>
After seeing your update and the various comments, I start to think that you just want to get the siblings of this
. If you just want an element's siblings, use jQuery's siblings() function. This function optionally accepts a selector to get only specific siblings. Anyway, siblings implicitly excludes this
itself.
$('td').on('click', function() {
$(this).css('color', 'red')
$(this).siblings().css('color', 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>Cell1</td><td>Cell2</td></tr>
<tr><td>Cell3</td><td>Cell4</td></tr>
<tr><td>Cell5</td><td>Cell5</td></tr>
</table>