Solve - $(...).length is not a function jQuery Error

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

Solve - $(...).length is not a function #

The "$(...).length is not a function" jQuery error occurs when trying to call the length property as a function. To solve the error, omit the parenthesis when accessing the jQuery length property, e.g. $('#list li').length.

jquery length is not a function error

index.js
$(document).ready(function () { // โ›”๏ธ BAD - remove parenthesis after length console.log($('#list li').length()); // โœ… GOOD - accessing length property correctly console.log($('#list li').length); });

Here's a complete working example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <ul id="list"> <li>first</li> <li>second</li> <li>third</li> </ul> <!-- โœ… load jQuery โœ… --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <!-- โœ… load your JS file โœ… --> <script src="index.js"></script> </body> </html>

In the html file, we load the jQuery library, then load our JS file (index.js in the example).

We defined an unordered list on which we'll use the length property. Here's the code for the index.js file.

index.js
$(document).ready(function () { console.log($('#list li').length); });

After the DOM is loaded, we log the result of accessing the length property on the list items of the unordered list.

If you load the page and open your console, you'll see the number 3 - the length of li elements in the list.

If you're still getting the error, make sure you only load the jQuery library once on the page. Loading the library twice re-runs the initialization process and can lead to all sorts of bugs.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee