1

I am just simply trying to append a variable to an html element using jquery. Where am I going wrong?

var simple = $('<p> hello </p>');
$('.easy').append(simple);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="easy"> </div>

Thanks so much!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
maxccpage
  • 21
  • 3
  • 5
  • 3
    I placed your code in an executable snippet and it appears to work fine. If your code isn't working you need to ensure you've added a reference to jquery.js in the page and also that you're running your code in a document.ready event handler (which the snippet is adding automatically) – Rory McCrossan Nov 24 '17 at 19:42
  • Yup, it was the document.ready I was missing, thanks! – maxccpage Nov 24 '17 at 19:52

2 Answers2

2

Your var simple should be a string, without the $.

var simple = "<p>hello</p>";
$(".easy").append(simple);
pmkro
  • 2,542
  • 2
  • 17
  • 25
  • 2
    This may be better code, but it's not an issue that would stop the OPs code working - as you can see from the snippet in the question – Rory McCrossan Nov 24 '17 at 19:43
  • 2
    append works with both html strings and jQuery elements. I see no benefit to this answer. – iGanja Nov 24 '17 at 19:58
1

var simple = '<p> hello </p>';
$('.easy').append(simple);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="easy"> </div>

If you want to create HTML template, you can also use backticks.

Lwin Htoo Ko
  • 2,326
  • 4
  • 26
  • 38