×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery :only-child Selector

jQuery | :only-child Selector: Learn about the jQuery :only-child Selector with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on November 04, 2022

:only-child Selector

In jQuery, selectors are a parameter through which we can select the HTML element. Selectors can comprise – class names, ids, tag names, attributes, etc. Basically, by using selectors, the appropriate HTML-DOM element can be selected and hence performed actions on it. Here, we are discussing the jQuery :only-child Selector.

The jQuery :only-child selector helps to select the only child occurrence which means the single child present of the specified tag in their parent elements. It is used along with some tag names prepended to it. It will return the only child of the parent

:only-child Selector Syntax

$('elementName:only-child');

Once the elements are selected, you can access them and perform the actions that you want to perform on them. The example given below shows the selection of the only child element of the 'div' tag on click by passing the appropriate selector.

jQuery :only-child Selector Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <h2>jQuery - Only Child Selector</h2>
    <p>Click the button and get the only child of the selected element.</p>
    <button>Only Child Selector</button>
    <hr>
    <div>
      <div>Div One</div>
      <div>Div Two</div>
    </div>
    <br>
    <div>
      <div>Div Three</div>
      <div>Div Four</div>
    </div>
    <br>
    <div>
      <div>Div Five</div>
    </div>
    <br>
    <div>
      <div>Div Six</div>
      <div>Div Seven</div>
    </div>
    <br>
    <hr>
  </body>
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('div:only-child').css({'color':'red', 'font-size':'larger'});
        });
    });
  </script>
</html>

Output:

Example 1: jQuery :only-child Selector


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.