Main Tutorials

jQuery – Not selector example

In jQuery, the “not” is used to select all elements that do not match the selector.

Examples

  1. $(‘p:not(.class-p1)’) – selects all elements matched by <p> that do NOT have a class name of “class-p1”.
  2. $(‘li:not(:only-child)’) – selects all elements matched by <li> that are NOT the only child of their parent.
  3. $(‘li:not(:first-child)’) – selects all elements matched by <tr> that are NOT the first child of their parent.

jQuery Example

A simple example to show the use of the jQuery “not” selector, click on the buttons to play around it.


<html>
<head>
<title>jQuery not example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>

<body>

<h1>jQuery not example</h1>

<ul class="class-ul">
	<li>class-ul - #1</li>
	<li>class-ul - #2</li>
	<li>class-ul - #3</li>
	<li>class-ul - #4</li>
	<li>class-ul - #5</li>
</ul>

<ul id="id1">
	<li>id1 - #1</li>
</ul>

<p class="class-p1">
	class - #p1
</p>

<p class="class-p2">
	class - #p2
</p>

<button>p:not(.class-p1)</button>
<button>li:not(:only-child)</button>
<button>li:not(:first-child)</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li,p").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
man
11 years ago

$(‘li:not(:first-child)’) – selects all elements matched by that are NOT the first child of their parent.

-> I think – selects all elements matched by that are NOT the first child of their parent.

Manish Tuteja
11 years ago

In the line :-

$(‘li:not(:first-child)’) – selects all elements matched by that are NOT the first child of their parent.

shouldn’t it be instead of ?

Manish