Reputation: 307
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?
Upvotes: 3
Views: 30301
Reputation: 96810
JavaScript:
function myFunction() {
var i = 9;
return i;
}
$('myElement').innerHTML = myFunction();
HTML:
<span id="myElement"></span>
Upvotes: 0
Reputation: 39
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.
Upvotes: -1
Reputation: 674
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.
Upvotes: 1
Reputation: 95334
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.
Upvotes: 1
Reputation: 28906
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.
Upvotes: 1
Reputation: 2812
You can use innerHTML to embed the i value in a div or span element.
Upvotes: 1