4

I have a variable that I would like to append added to some other text. My first though was this:

var wood  = 5
$(wood+"<p>bits of wood left</p>" ).appendTo("#notifications");

Then I tried this:

var wood  = 5
var woodLeft=(wood + "wood left");
$(woodLeft).appendTo("#notifications");

But that doesn't work either. Any ideas of how to get this to function?

2 Answers 2

2

The problem is jQuery thinks you're passing a selector to it, and then throws an error Uncaught Error: Syntax error, unrecognized expression: 5<p>bits of wood left</p>
Solution: Tell jQuery to explicitly parse it as html.

var wood  = 5
$($.parseHTML(wood+"<p>bits of wood left</p>" )).appendTo("#notifications");

http://jsfiddle.net/rg7trxov/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that really helped out! How would I go about getting the number on the same line?
By not using a block level tag like a p, you can use a span for instance.
2

I would do it this way:

$("#notifications").append(wood+"<p>bits of wood left</p>" );

http://jsfiddle.net/s3f1vq72/

3 Comments

.. and for markups' sake I would put wood inside the <p>
Eric Mahieu How would I do that?
It really depends on what you want to do... but you can say "<p>bits of wood"+wood.toString()+"</p>".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.