OpenJS Foundation - openjsf.org · api.jquery.com

parent selector

Description: Select all elements that have at least one child node (either an element or text).

  • version added: 1.0jQuery( ":parent" )

This is the inverse of :empty.

One important thing to note regarding the use of :parent (and :empty) is that child nodes include text nodes.

The W3C recommends that the <p> element have at least one child node, even if that child is merely text (see https://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

To obtain the parents or ancestors of an existing jQuery set, see the .parent() and .parents() methods.

Additional Notes:

  • Because :parent is a jQuery extension and not part of the CSS specification, queries using :parent cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :parent to select elements, first select the elements using a pure CSS selector, then use .filter(":parent").

Example:

Finds all tds with children, including text.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>parent demo</title>

<style>

td {

width: 40px;

background: green;

}

</style>

<script src="https://code.jquery.com/jquery-4.0.0.js"></script>

</head>

<body>

<table border="1">

<tr><td>Value 1</td><td></td></tr>

<tr><td>Value 2</td><td></td></tr>

</table>

<script>

$( "td:parent" ).fadeTo( 1500, 0.3 );

</script>

</body>

</html>

Demo:

Read the original on api.jquery.com ↗