'how to render a JS variable into a html element
I am new to Javascript and want to be able to display a JS variable onto my page without the user going into the console as it is neater, and I find a lot of people don't know about the console, and I don't want to use the alert()
code. Can anyone help?
Solution 1:[1]
The code below accesses the paragraph with id "test" and print the value of "testVariable" into it.
var testVariable = "hello";
document.getElementById("test").innerHTML = testVariable;
<p id="test"></p>
Solution 2:[2]
I think this is what you need but this example is very simple i recommend you to google more and to keep open the JavaScript Doc for any questions.
The definition for innerHTML
.
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
// Your variable
let name = "Jhon"
// Get the HTML tag by ID and set the innerHTML
document.getElementById('name').innerHTML = name;
<div class="container">
<p>Hello <span id="name"></span></p>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Archit Gargi |
Solution 2 | Rafael |