Reputation: 10380
Why does this code output 4 and all the other content does not get outputted?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var par = $("p");
document.write(par.length);
});
</script>
</head>
<body>
<p>I am one</p>
<p>I am two</p>
<p>I am three</p>
<p>I am four</p>
</body>
</html>
Upvotes: 0
Views: 67
Reputation: 895
Create another tag inside body.
<div id="plength"></div>
Then add code like below
$(document).ready(function() {
var par = $("p");
$('#plength').text(par.length);
});
Running example here http://jsfiddle.net/rajeshmepco/Bk6bZ/
Upvotes: 0
Reputation:
You've executed your script when the document is ready - good. But document.write() will write directly to the exisitng document, replacing what is there, so your paragraphs disappear.
Since you're using jQuery you would do better to have jQuery add the item for you:
$("body").append("<p>Paragraph count:"+$("p").length+"</p>");
Upvotes: 0
Reputation: 388316
when document.write is called after document ready, it removes all contents from the document because it calls document.open which wipes out all the content
Looks like what you want is to just append the par.length
to the body
$(document).ready(function() {
var par = $("p");
$('body').append(par.length);
});
Upvotes: 3