<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function count(){
alert("There are " + $("p").length() + " paragraphs.");
}
</script>
</head>
<body>
<p>This is first para</p>
<p>This is second para</p>
<p>This is third para</p>
<p>This is fourth para</p>
<form>
<input type="button" value="Count Paragraphs" onclick="count()"></input>
</form>
</body>
</html>
ERROR
Uncaught TypeError: $(…).length is not a function
at count (index.html:11)
at HTMLInputElement.onclick (index.html:22)
I think you’re looking for $("selector").size()
. Length is JavaScripts native property. Gotta love abstractions (just kidding)
Also, length is not a function
According to the .size() doc page, using length is the preferred solution.
So what is the correction in that code?
alert(“There are " + $(“p”).length() + " paragraphs.”);
Look at the documentation.
length is not a function, it’s a property.
Also if my memory doesn’t fail you cannot use length off a jQuery object ?
Ahh yes - the answer is to just remove the function invoking parenthesies.
Yes you can, that is now the preferred way of getting the number of matched elements.
https://api.jquery.com/length/
1 Like
ralphm
10
In case the above comments weren’t explicit enough, you just need to remove the ()
from .length()
:
alert("There are " + $("p").length + " paragraphs.");
3 Likes
system
Closed
11
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.