Hi
I expected to see: n = 3. But I see n = 0
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/libs/jquery-1.9.0/jquery.min.js'></script>
<script>
var n = $( "[id^='user']" ).length;
console.log( n );
</script>
</head>
<body>
<form>
<input id="userName" type="text" />
<input id="userId" type="text" />
<input id="userPhone" type="text" />
</form>
</body>
</html>
Thank you advance!
And Why doesn’t it work?
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/libs/jquery-1.9.0/jquery.min.js'></script>
<script>
var n = $( "[id*='zombie']" ).length;
console.log(n);
</script>
</head>
<body>
<div id="greenzombie"></div>
<div id="zombieman"></div>
<div id="madscientist"></div>
</body>
</html>
8Observer8:
And Why doesn’t it work?
Because you are trying to reference elements before they exist in the DOM.
Place your scripts at the bottom of your page, then the DOM will be ready.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Zombies</title>
</head>
<body>
<div id="greenzombie"></div>
<div id="zombieman"></div>
<div id="madscientist"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var n = $( "[id*='zombie']" ).length;
console.log(n);
</script>
</body>
</html>
Thank you very much!
It works fine too:
<script>
$( function() {
var n = $( "[id^='user']" ).length;
console.log( n );
} );
</script>
Glad to help
A further tip:
If you put your JS just before the closing body tag (as I did in my example), then you don’t need to wrap everything in a callback, as the DOM will be ready by definition:
<script>
var n = $( "[id^='user']" ).length;
console.log( n );
</script>
</body>
</html>
Good idea, thanks! I will select a comfortable way later