I want to use a variable in a string. I have tried to do it many times, but it is only getting the variable name.
Concatenating can be done with +
as follows.
$('.html').html("<div class='new' id='" + id + "'>jitender</div>");
Reference:
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
I felt this to be a more easy and efficient way. (use ``)
$(".html").html(`<div class="new" id="${id}">jitender</div>`)
The correct way of doing this is is by taking advantage of jQuery's HTML constructor to perform all the necessary escaping for you:
$("a").click(function() {
var id= $(".id").html();
// create new element
$('<div>', {
class:'new',
id: id,
text: 'jitend'
}).appendTo('.html'); // and append it
});
Javascript does not support expanding variables inside double quotes. Close (and reopen) the quotes and use the + operator, as you already did.
"<div class='new' id='" + id + "'>"
here id
is variable
Try this
$(".html").html("<div class='new' id='"+id+"'>jitender</div>")