Ved Tiwari
Ved Tiwari

Reputation: 310

Create H1 element in div jQuery

I want to a <h1></h1> element in a div element in HTML with jQuery. How do I do this?

function show() {
  let text = "greetings"
  let divElem = document.getElementById("hello");
  divElem.innerHTML = '<h1>${text}</h1>'
}
<div id="hello"></div>
<button onclick="show()">show</button>

Basically, I want to make an h1 element in the div element which displays the string contained in the text variable, "greetings" how do I do this?

Upvotes: 0

Views: 1022

Answers (2)

S&#248;lve
S&#248;lve

Reputation: 4406

You can use the Jquery .html() method.

Also, you have to use backticks instead of quotes. (`) in order to use templating inside a "string". This is called Template literals. You can read more about them here

function show() {
  let text = "greetings"
  $( "#hello" ).html( `<h1>${text}</h1>` );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hello"></div>
<button onclick="show()">show</button>

Upvotes: 2

AmirNorsou
AmirNorsou

Reputation: 1131

Do you need to ` instead of ' ?!

Also can read about it in this link : Template literals (Template strings).

function show() {
  let text = "greetings"
  let divElem = document.getElementById("hello");
  divElem.innerHTML = `<h1>${text}</h1>`
}
<div id="hello"></div>
<button onclick="show()">show</button>

Upvotes: 5

Related Questions