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

lengthReturns: Integer

Description: The number of elements in the jQuery object.

  • version added: 1.0length

The number of elements currently matched. The .size() method will return the same value.

Example:

Count the divs. Click to add more.

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

27

28

29

30

31

32

33

34

35

36

37

38

39

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>length demo</title>

<style>

body {

cursor: pointer;

}

div {

width: 50px;

height: 30px;

margin: 5px;

float: left;

background: green;

}

span {

color: red;

}

</style>

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

</head>

<body>

<span></span>

<div></div>

<script>

$( document.body )

.on( "click", function() {

$( document.body ).append( $( "<div>" ) );

var n = $( "div" ).length;

$( "span" ).text( "There are " + n + " divs." +

"Click to add more.");

} )

// Trigger the click to start

.trigger( "click" );

</script>

</body>

</html>

Demo:

Read the original on api.jquery.com ↗