How to use variable in string in jquery

I want to use a variable in a string. I tried to do this many times, but it only gets the variable name.

<head> <script type="text/javascript" src="jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){ $("a").click(function(){ var id= $(".id").html(); $('.html').html("<div class='new' id=+id+>jitender</div>") }); }); </script> </head> <body> <div class="wrap"> <a href="#">Make Html</a> <div class="html"></div> <div class="id">first</div> </div> </body> 
+6
source share
6 answers

Concatenation can be performed using + as follows.

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

Reference:

+15
source
 <script type="text/javascript"> $(function(){ $("a").click(function(){ var id= $(".id").html(); $('.html').html("<div class='new' id='"+id+"'>jitender</div>"); }) }) 

+1
source

The right way to do this is to use the jQuery HTML constructor to do all the necessary things for you:

 $("a").click(function() { var id= $(".id").html(); // create new element $('<div>', { class:'new', id: id, text: 'jitend' }).appendTo('.html'); // and append it }); 
+1
source

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

0
source

try it

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

Javascript does not support variable expansion inside double quotes. Close (and reopen) the quotation marks and use the + operator, as you already did.

"<div class='new' id='" + id + "'>"

here id is a variable

-2
source

Source: https://habr.com/ru/post/918163/


All Articles