If I have a much simplified JavaScript method such as this:
function myfunction() {
var i = 9;
}
Is there any way I can get the value of i
into HTML such that when the web page with this method is called, the value 9
is displayed in a div or span element?
If I have a much simplified JavaScript method such as this:
function myfunction() {
var i = 9;
}
Is there any way I can get the value of i
into HTML such that when the web page with this method is called, the value 9
is displayed in a div or span element?
7 Answers
Reset to default 5You can write document.getElementById("some ID").innerHTML = i
Hi :D you can try the following using JQuery:
var i = 9;
$('#spanId').text(i);
or the classic old-fashion way:
var tmp= document.getElementById('spanId');
tmp.textContent = id;
I hope this helps.
You can use innerHTML to embed the i value in a div or span element.
myfunction() current does not return its value. However, if you want to get the value when the page is "called" (loaded) you can do this:
function myfunction() {
var i = 9;
return i;
}
And in the markup:
<body onload="document.getElementById('id_of_your_div').innerHTML = myfunction()">
Please note that innerHTML has cross-browser issues, so you may want to use a library function such as jQuery's html() for reliable results.
Yes, you can assign an id
to your <div>
or <span>
and set its innerText
/textContent
property to your value.
window.onload = function() {
var content = myfunction();
var tag = document.getElementById('displayVar');
if(typeof tag.innerText == "undefined") {
tag.textContent = content;
} else {
tag.innerText = content;
}
}
Do not use innerHTML
if you do not want the HTML code of your value to be parsed (or if you don't expect any HTML value).
And no, you do not need a 31kb library to do that kind of work (just in case there's a bunch of "jQuery can do that!" answers).
Note that you must also modify myfunction()
so that it returns the current value. A simple return i;
statement in the function will do the trick.
JavaScript:
function myFunction() {
var i = 9;
return i;
}
$('myElement').innerHTML = myFunction();
HTML:
<span id="myElement"></span>
you can also use jQuery to simplify the syntax following are the three ways you can do that using jQuery,
1) $('span').text(i)
2) $('#someid').text(i) //someid = value of id attribute of span tag.
3) $('.someclassname').text(i) //someclassname = class name for the span tag.
- Also using jQuery means forcing the users have to download addition jQuery lib when the page loads. That might slow down the page depending on the connection speed of the users. You might want to consider that while selecting between jQuery and plain JavaScript