JQuery appendTo() to html() to allow replace

706 Views Asked by At

I have the following

$('.toggle_questions').appendTo('#'+sectionId).show();

Which works perfectly to append my div (.toggle_questions). However, I want it to replace rather than add each time.

From my understanding this is done through html() rather than appendTo() ? I have only found examples adding simple <p> codes and not actual <div> 's

I have changed it to this but it won't seem to do anything:

$('#'+sectionId).show().html($('.toggle_questions')).show();

The show() is needed as it is set to hidden to start with.

Where have I gone wrong? Thanks!

2

There are 2 best solutions below

1
Johnny Kutnowski On BEST ANSWER

I would save the content of $('.toggle_questions') on every occurrence and apply it like this:

var content = $('.toggle_questions').html();
$('#' + sectionId).html(content).show()

It's a much cleaner code and easier to maintain.

0
Rajaprabhu Aravindasamy On

Try to pass html string in to .html(),

$('#'+sectionId).html($('.toggle_questions').html()).show();

.html() wont accept jquery object as its parameter.

But appendTo() will move the original object. If you want to do the same thing using .html(), then you have to remove it manually after setting the html string.