Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to use a variable in a string in jQuery?

I am working on jQuery and learning the usage of variables correctly. How can I use a variable in a string in jQuery? I am having the following string,

Learners

On the click of a link, I want to show the string “Hello Learners” using variable in string.


1 Answer
Ricky Barnes

jQuery is a JavaScript library introduced to make development with JavaScript easier. Let us see how to use variable in a string using the html() method.

You can try to run the following code to learn how to use variable in a string in jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(function(){
      $("a").click(function(){
        var id= $(".id").html();
        $('.myclass').html("<br><div class='new' id='" + id + "'>Hello</div>");            
      });
   });
</script>
</head>
<body>
   <div class="wrap">
      <a href="#">Click me</a>
      <div class="myclass"></div>
      <div class="id">Learners</div>
   </div>
</body>
</html>

Live Demo

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.