简体   繁体   中英

How I can show a Variable Valor in to a h1 in html and js

I'm new to coding things, and I want to learn a lot, so I found Stackoverflow, to solve my question...

The code I have is:

<h1 class="Result" id="result">0</h1> 

Now, I do a basic JS File:

const number = 0;
var elem = document.getElementById('result');

And, now I don't know what to do, to display it in the h1, if someone can help me I would really appreciate it.

这些是您可以动态添加值的一些方法。

document.getElementById('result').innerHTML = number;

document.getElementById('result').innerText = number;

document.getElementById('result').textContent = number;

You have an h1 with an id of 'result', side note always have different id and class name so you dont confuse yourself.

<h1 class="Result" id="result">0</h1>

For your javascript:

var elem = document.getElementById('result')

So now that you have placed the content of the h1 inside a variable you can display it using:

console.log(elem)

The reason your code didn't work was that you didn't use the console.log of a variable to display the content inside the variable.

First you need to grab the h1 tag using the document.getElementById() method like you did.

Than you use the innerHTML property to display text.

Here is the full code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
javaScript example
</title>
</head>
<body>
<button onclick="myFunction()">
click to see message
</button>
<h1 Id="message" class="message">
</h1>
<script>
function myFuntion(){
var message = "hello, how are you\?";
document.getElementById("message").innerHTML = message;
}
</script>
</body>
</html>
  
First we created a button that has a function attach to it, than we create an function that will store the message. When the button is clicked, the message will show in the h1 tag.
Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM