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?

2
  • 1
    String should be in single-quotes Commented Apr 15, 2016 at 6:28
  • jsfiddle.net/rayon_1990/f3btxg8j Commented Apr 15, 2016 at 6:29

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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")'

Comments

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> 

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.