简体   繁体   中英

Why jQuery html works like replaceWith when using with form?

I have form with id push-message-form and ajax call to server returns new form html to replace with. push-message-form id set on form itself, like:

<form id='push-message-form'>form content</form>

and ajax response html looks same.

From jQuery docs I understood that: html() will replaces the contents of the element, while replaceWith() replaces the actual element.

http://api.jquery.com/html/

http://api.jquery.com/replaceWith/

But I'm using

$('#push-message-form').html('<form id='push-message-form'>content</form>')

and it replaces form itself (whilst it should add another form inside current one).

The question is why html() works as replaceWith() in this case?

Update

Some answers suggests use append, sorry if it's not clear. But I don't want to append. I want to replace form with new one returned from server (keeping it's id), and replaceWith() does work just fine.

The question is why html() works too here. Since it should replace only content, but it replaces tag too.

You should be using .append() to add content to the container calling .html() is going to replace whatever is inside that container with the value you enter:

Also you're trying to append the form with the same id so you should use a class or change the id name

This:

$('#push-message-form').append('<form class="push-message-form">content</form>')

Instead of this:

$('#push-message-form').html('<form id='push-message-form'>content</form>')

.html() acutally clears the HTML inside the element & then places your new HTML in it. While you need .append() to actually make you new HTML added in the Current HTML

$('#push-message-form').append('<form id='new-form-id'>content</form>')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM