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 the Author

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

Comments

avatar
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
manManish TutejajQuery Tutorials | J2EE Web Development Tutorials Recent comment authors
newest oldest most voted
man
Guest
man

$(‘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
Guest
Manish Tuteja

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

trackback
jQuery Tutorials | J2EE Web Development Tutorials

[…] Not selector select all elements that do not match the selector. […]