-2
<html>
    <head>
    </head>

    <body>
        <script>    
            var myFunction = function(){
                return "hello world";
            }
        </script>    
        myFunction();        
    </body>
</html>

I just finished the code academy course on javascript but it didn't taught me how to code javascript inside html. I need to display hello world inside the html's tag using the function is this possible? my friend told me I need jquery just to do this.

2
  • 1
    wrap it in <script> tag Commented Jul 20, 2015 at 7:11
  • use document.write to write inside HTML in place of return Commented Jul 20, 2015 at 7:16

3 Answers 3

2

You have to specifically tell the webpage to execute your function when it's loaded.

Instead of returning the string I believe you'd like to write it in the body of the webpage.

This is a simple way to do so :

<html>
    <head>
        <script>
            var myFunction = function(){
                document.body.innerHTML = "hello world";
            }
        </script>
    </head>
    <body onload='myFunction();'>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

4 Comments

"Also script tags must be contained in head tag." That's simply not true.
However, credits where due, this is one of the few answers that adds the returned value to the HTML without the awful document.write.
@Cerbrus I've removed the script in head tag sentence.
Excellent :-) Now this is a decent answer.
-1
<html>
<head>
</head>
<body>
<Script>

function myFunction(){
    document.write("hello");
}


</script>
<Script>
    myFunction();
    </Script>

</body>
</html>

This was asked already How to call a javascript function within an HTML body

I just replace the

tag with document.write

1 Comment

Don't use document.write. It's unpredictable.
-2

Try this

<html>
<head>
</head>
<body onload='myFunction()'>

<script type="text/javascript">
    var myFunction = function(){
       return "hello world";
    }
</script>

</body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.