Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable in string in jQuery

Tags:

html

jquery

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.

<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>
like image 755
Jitender Avatar asked Jun 15 '12 10:06

Jitender


Video Answer


2 Answers

Concatenating can be done with + as follows.

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

Reference:

  • https://developer.mozilla.org/en/JavaScript/Reference/Operators/String_Operators
like image 109
VisioN Avatar answered Nov 02 '22 10:11

VisioN


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

like image 24
Kent Munthe Caspersen Avatar answered Nov 02 '22 10:11

Kent Munthe Caspersen