How to use variable in string in jQuery

Concatenating can be done with + as follows.

$(".html").html('<div class="new" id="' + id + '">jitender</div>");

or in the modern world you can use template strings:

$(".html").html(`<div class="new" id="${id}">jitender</div>`);

The more jQuery-oriented approach would be:

var id = "some-id";

$("<div>", {
    "class": "new",
    id: id,
    text: "jitender"
}).appendTo(".html");
.new {
    background: #f0f;
}
#some-id {
    color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="html"></div>

References:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#string_operators
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

You can also use template literals:

$('.html').html(`<div class='new' id=${id}>jitender</div>`)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Tags:

Html

Jquery