Mr Morgan
Mr Morgan

Reputation: 307

How to get value of JavaScript into HTML span?

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

Answers (7)

David G
David G

Reputation: 96810

JavaScript:

function myFunction() {
    var i = 9;
    return i;
}

$('myElement').innerHTML = myFunction();

HTML:

<span id="myElement"></span>

Upvotes: 0

Bunty
Bunty

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.

  • 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

Upvotes: -1

mario.tco
mario.tco

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

Andrew Moore
Andrew Moore

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

George Cummins
George Cummins

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

Srikanth Venkatesh
Srikanth Venkatesh

Reputation: 2812

You can use innerHTML to embed the i value in a div or span element.

Upvotes: 1

SLaks
SLaks

Reputation: 887453

You can write document.getElementById("some ID").innerHTML = i

Upvotes: 5

Related Questions