-2

I'm new to coding. I'm trying to make a website to track my homework. I want it to show what I have to do. This is my code.

<p id="demo">To do now.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "do"'>Click Here!</button>

var do="5";

how do I get "To do now." to 5.

Andrew
  • 11
  • 1
  • Does this answer your question? [How to get the HTML for a DOM element in javascript](https://stackoverflow.com/questions/1763479/how-to-get-the-html-for-a-dom-element-in-javascript) – shreyasm-dev Nov 03 '20 at 02:37

3 Answers3

1

You can't have Javascript just floating in an HTML file, as your browser won't know what to do with it. All Javascript should either be enclosed by <script> tags or in an external file and referenced with a <link> tag.

Correct me if I'm wrong, but as I understand it, you want the "To do now." to change to 5.

If so then you don't need your do variable. You would just change your onclick attribute value as follows:

<button type="button" onclick='document.getElementById("demo").innerHTML = "5"'>Click Here!</button>

Alternatively, if you wanted to have the text to change to 5 using a Javascript variable, you would open a script tag and insert a function to do so like this:

<script type="text/javascript">
  function changeText() {
    var doo = 5;
    document.getElementById('demo').innerHTML = doo;
  }
</script>

<p id="demo">To do now.</p>

<button type="button" onclick="changeText()">Click Here!</button>

I'm not too sure why you want to do this but I gave you this option anyway incase you did.

As you can see, I changed the do variable that you used to doo as you can't use the first version as a variable name. This is due to the fact that we use do as a keyword for loops. Check out w3's page on do/while loops here.

If you say you're new to programming then I thoroughly recommend using w3 schools HTML, CSS, and Javascript tutorials as once completed, you should have a much better understanding about how Javascript interfaces with HTML.

jacc_01
  • 310
  • 1
  • 2
  • 10
0

do is a predefined word in JavaScript, so you cannot use it as a variable. try something else. you can try this

<p id="demo">To do now.</p>

<button type="button" onclick="var doit='5'; document.getElementById('demo').innerHTML = doit;">Click Here!</button>
Mijanur Rahaman
  • 353
  • 1
  • 5
  • 19
0

I don't recommend declaring functions in the html structure. It is better to put the JavaScript logic in the file separately, as in my example.

var inner = '5';

document.querySelector('button').onclick = function() {
  document.getElementById("demo").innerHTML = inner;
}
<p id="demo">To do now.</p>
<button type="button">Click Here!</button>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25