How to Insert a Variable in HTML and JavaScript?

Estimated read time 2 min read

You can insert a variable in HTML and JavaScript by using the JavaScript document.write method or by setting the innerHTML property of an element.

Here’s an example using the document.write method:

  var name = "John Doe";
  document.write("<p>Hello " + name + "!</p>");

In this example, a variable name is declared and assigned the value "John Doe". The document.write method is then used to write a paragraph containing the text “Hello John Doe!”.

Here’s an example using the innerHTML property:

<div id="myDiv"></div>

  var name = "John Doe";
  document.getElementById("myDiv").innerHTML = "<p>Hello " + name + "!</p>";

In this example, a <div> element with an id of "myDiv" is created in the HTML. The JavaScript code uses document.getElementById to retrieve the <div> element and set its innerHTML property to a string that includes the name variable.

This means that the text “Hello John Doe!” will now be displayed inside the <div> element in the HTML page.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply