JQuery Selector only-child

From CoderLearner
Jump to: navigation, search

Description

Select element that it is the only child of its parent.

Syntax

$(":only-child")
$("parent child:only-child")

Example 1

<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Select</title>
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <style>
         .mark {
            color:red;
         }
      </style>
      <script>
         $().ready(function() {
            $('div p:only-child').addClass("mark");
         });
      </script>
   </head>
   <body> 
      <div id="top1">
         <p>Div-P</p><!-- the only child -->
      </div>
      <div>
         <span>
            <a href="#">Div-Span-A</a>
         </span>
      </div>
      <div>
         <div>
            <p>Div-Div-P</p><!-- the only child -->
         </div>
         <div>
            <span>Div-Div-Span</span>
         </div>
      </div>
   </body>
</html>

Try It