Display javascript variable in html body

here is my sample code:

<script> function smth(){........} var name = smth('fullname'); var hobby = smth('hobby'); </script> 

I need to display it normally in the html package. However, every way I tried gave me a warning window or just didn't work. I did not find a similar solution. I know that the above method gives alert windows, but I just wanted to show you how I get my variables. Thanks in advance.

0
source share
4 answers

One of the most common ways to do this is to use innerHTML . Suppose you declare <p> as <body> as output, then you can write:

 <script> function smth(){........} var name=smth('fullname'); var hobby=smth('hobby') var out=document.getElementById("output"); out.innerHTML=name; (or you may write hobby) </script> 
+1
source

So you want to add text to <body> ?

 function smth(str) { return document.body.appendChild(document.createTextNode(str)); } 

It uses the following DOM methods.

Please note that it will not introduce formatting (e.g. linear brakes <br /> ) if you want the ones you will need to add as well.

0
source

With this approach, you can target an item by ID and insert whatever you want into it, but the solution proposed by Paul S is simpler and cleaner.

 <html> <head> <script type="text/javascript"> var myVar = 42; function displayMyVar(targetElementId) { document.getElementById(targetElementId).innerHTML = myVar; } </script> </head> <body onload="displayMyVar('target');"> <span id="target"></span> </body> </html> 
0
source

try using:

 var yourvar='value'; document.body.innerHTML = yourvar; 
0
source

Source: https://habr.com/ru/post/1012714/


All Articles