1

here is my approximate code:

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

    </script>

I need to display it normally in the html body. However, every way I tried gave me an alert window or it simply didn't work. I didn't find the similar solution. I know that the way above gives an alert windows as well, but I just wanted to show you the way I get my variables. Thanks in advance.

2
  • 1
    Try document.write(name); Commented May 24, 2015 at 18:39
  • Possible duplicate of This Commented May 25, 2015 at 4:50

4 Answers 4

2

So you want to append some text to <body>?

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

This is making use of the following DOM Methods

Please notice that it won't introduce formatting (such as line brakes <br />), if you want those you'd need to add them too.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! could you be specific please
1

With this approach you can target an element by ID and insert whatever you like inside it, but the solution suggested from Paul S is more simple and clean.

<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>

4 Comments

it works..partly, as first I still get the alert window!
What do you mean with alert window?
My bad, I mean a pop up
You are probably calling the "alert()" function somewhere in your code
1

One of the very common ways to do this is using innerHTML. Suppose you declare a <p> in the <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>

Comments

0

try using:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.