1

In the following code document.write() function is not able to take string as its argument,

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html> 

The problem seems to be that there are already quotations around "document.write(5 + 6)".

So how do I add a usual text string to it?

user31782
  • 5,979
  • 8
  • 54
  • 117

4 Answers4

3

Try with single quotes for string as below:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write('Hello world')">Try it</button>

</body>
</html>
Mani
  • 899
  • 6
  • 15
3

You may better use document.getElementById, because document.write is bad practice.

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<p id="result"></p>
<button onclick="document.getElementById('result').innerHTML=5 + 6">Click Me!</button>
Community
  • 1
  • 1
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
1

you can do this - let the string be in single quotes.

onclick="document.write('5 + 6')"

Note: You can interchnage single and double quotes. This also works

onclick='document.write("5 + 6")'

Lingaraju E V
  • 484
  • 2
  • 8
0

Try this..

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick='document.write(5 + 6)'>Try it</button>

</body>
</html> 
smraj
  • 152
  • 8