How To Use JavaScript Variable In HTML
Last Updated : Mar 11, 2024
IN - JavaScript HTML | Written & Updated By - Ashish

In this article we will show you the solution of how to use JavaScript variable in HTML, we are going to use some JavaScript properties.
.createElement: this property is used to create an HTML variable using JavaScript.
- .createTextNode: this property is used to create a text node.
- .appendChild: this is used to create a new node.
Also using the .style property to use to add style to HTML element using JavaScript.
Step By Step Guide On How To Use JavaScript Variable In HTML :-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> How to use JavaScript variable in html</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
<style>
h1 {
color : rgb(95, 194, 95) ;
font-size: 25px;
font-weight : bolder ;
}
</style>
</head>
<body>
<center>
<h1> TALKERSCODE </h1>
<h3> How to use JavaScript variable in html </h3>
</center>
<script>
//generate div element using javascript
const div = document.createElement("div") ;
//set text content
const text = "hello" ;
const divContent = document.createTextNode(text) ;
//add text to div
div.appendChild(divContent);
//set style
div.style.color = "red";
div.style.height = "50px";
div.style.width = "50px";
</script>
</body>
</html>
- To write HTML code <! DOCTYPE html> to mention which version of the HTML file is written in.
- Then we have to write the <html> tag used to define the root of an HTML document. And also write the ending tag </html>.
- <head> tag used here to use to contain the metadata about the HTML file and end it with </head> tag
- Then <title> tag is used to set the title of the HTML document and end it with </title> tag.
- In order to style the HTML page, we'll utilize an external CSS file
- using <style> tag to add CSS
- <h1> tag used to add a heading close it with </h1> tag
- <script> tag is created write JavaScript within it.
- First, we will create a <div> element in JS using the document.createElement() by a constant div. We can use this method to create HTML tags
- Again create a constant using const of text and add some text. Add text content divContent with document.createTextNode().
- We can add the text constant to the <div> is created above by using .appendChild() by adding the divContent
- Now we can also set style using the .style method. for example, we add color, height, and width to the div element created above.
Conclusion :-
At last, here in conclusion, we can say that with this article’s help, we know How to use JavaScript variable in html in JavaScript.
I hope this article on how to use JavaScript variable in HTML helps you and the steps and method mentioned above are easy to follow and implement.













