Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Using variables with jQuery's replaceWith() method

Ok this one seems pretty simple (and it probably is). I am trying to use jQuery's replace with method but I don't feel like putting all of the html that will be replacing the html on the page into the method itself (its like 60 lines of HTML). So I want to put the html that will be the replacement in a variable named qOneSmall like so

var qOneSmall = qOneSmall.html('..........all the html'); 

but when I try this I get this error back

Uncaught SyntaxError: Unexpected token ILLEGAL

I don't see any reserved words in there..? Any help would be appreciated.

2 Answers

Hi David!

Is qOneSmall the class or ID of your element?

If so, you'll want to do something like this:

//store the html you would like to use in a variable as a string.
var contentHTML = '.......all the html'; 

// then use JQuery to set the html contents of your element to the contentHTML variable.
$('.qOneSmall').html(contentHTML);

You can even try it on this page if you open up the console. For instance I can replace your question paragraph with a variable like so:

var contentHTML = 'ALL THE HTML!!!!';
$('.question').html(contentHTML);
// Here I'm querying the element with the class 'question' (which is the class assigned to your question div) and replaces it with the contents of the variable 'contentHTML'.

You can copy and paste the code in your console to see what I mean.

If you're just trying to store the contents of the qOneSmall class/id and then use the JQuery replaceWith() method you can do this:

var $qOneSmall = $('.qOneSmall').html();

That will capture the html in the qOneSmall class. If it's an ID you're referring to then you would replace the period with a #.

You would then call the replaceWith method on the variable:

$qOneSmall.replaceWith(**whatever variable you stored the new html in**);

Hope that helps!

As it turns out the problem was that I wasn't escaping between lines correctly. To solve the problem I just put all the HTML on one line.

Ah, nice! Glad you figured it out then.