-1

I am trying to print something inside my html from a javascript. I don't know javascript much. I did this but it don't work:

<script type='text/javascript'>
//<![CDATA[
function title() {
var t = document.title;
document.write(t);
}
//]]>
</script>

<div>
      <span><script>title();</script></span>
</div>

3 Answers3

1

You can use element.innerHTML

let name = document.getElementById("name");

name.innerHTML = "hello world";
<div itemprop='review' itemscope='' itemtype='https://schema.org/Review'>
  <div itemprop='itemReviewed' itemscope='' itemtype='https://schema.org/Product'>
    <span itemprop='name' id="name" />
  </div>
</div>
1

If you fix your syntax error, and take away the CDATA you have a working bit of code. The reason why you still won't see any output is that, because you don't have a proper HTML document structure, there's no title to print...

Here's some updated code and an example of how to go about debugging using console.log().

<script type='text/javascript'>
    function title() {
        var t = document.title;
        // print the value of t to the console to test
        console.log( 'title is: ' + t );

        document.write(t);
    }
</script>

<div>
  <span>
      <script>title();</script>
 </span>
</div>
Steven
  • 192
  • 1
  • 8
0

You can define an external JavaScript file and link it to your html page like this.

<button onclick="myFunction()">Click me!</button>
<script src="app.js"></script>

and then define your function into app.js, like this:

function myFunction() {
    document.write("Hello, I'm here!");
}
maryam
  • 151
  • 1
  • 1
  • 12