Reputation: 11
I'm just trying to replace my P tag with a number list that counts from "1" to "5". But I'm making the numbering part a function. How do I call the function when replacing my P tag? Here is the code I wrote so far.
<script type="text/javascript">
function countNum() {
var i=1;
for (i=1;i<=5;i++) {
document.write(i+"<br />");
}
}
document.getElementById("paragraph").innerHTML=countNum();
</script>
</head>
<body>
<p id="paragraph">
Hello world.
</p>
</body>
Upvotes: 0
Views: 12848
Reputation: 11
Just use .call
instead of .innerHTML
:
document.getElementById("paragraph").call=countNum();
Upvotes: 1
Reputation: 350
<html>
<body>
<p id="paragraph">
Hello world.
</p>
<script type="text/javascript">
function countNum() {
var i=1;
for (i=1;i<=5;i++) {
document.write(i+"<br />");
}
}
document.getElementById("paragraph").innerHTML=countNum();
</script>
</body>
</html>
Try to put your script inside body below p tag.
Upvotes: 0
Reputation: 1786
You can make your function append to the paragraph like this.
function countNum () {
var elem = document.getElementById("paragraph");
var i = 1;
var innerElem;
for (i=1; i<=5; i++) {
innerElem = document.createElement("span");
innerElem.appendChild(document.createTextNode(i.toString()));
innerElem.appendChild(document.createElement("br"));
elem.appendChild(innerElem);
}
}
countNum();
Upvotes: 1
Reputation: 15230
<p id="paragraph">
Hello world.
</p>
<script type="text/javascript">
function countNum() {
var i=1;
var result = "";
for (i=1;i<=5;i++) {
result = result + i+ "<br />";
}
return result;
}
document.getElementById("paragraph").innerHTML=countNum();
</script>
Upvotes: 0
Reputation: 60835
I'm not really answering your question (two others already have), but another neat way to do what you want could be:
document.getElementById('paragraph').innerHTML = [1, 2, 3, 4, 5].join('<br>')
I use the join
method on the [1, 2, 3, 4, 5]
array.
Upvotes: 3
Reputation: 7887
you have to return your string, not to write to document directly:
function countNum() {
var i=1;
var string = "";
for (i=1;i<=5;i++) {
string += i+"<br />";
}
return string;
}
document.getElementById("paragraph").innerHTML=countNum();
Upvotes: 0
Reputation: 4764
function getHtml() {
var html = '';
var i=1;
for (i=1;i<=5;i++) {
html += i+"<br />";
}
return html;
}
Now use this method to assign to HTML.
document.getElementById("paragraph").innerHTML=getHtml();
Upvotes: 4