Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one html element with another

Tags:

jquery

I'm trying to replace a form inside a div with jQuery, consider following html:

<div>
  <form>
    <input type="text" value="some text here" id="friendship" class="not_friends">
  </form>
</div>

and following js code:

div = $("#friendship.not_friends").parent().parent();
$("form", div).remove();
$(div).add(response);

the "form" element is removed, as I want, but the new form (in 'response' string) isn't added to div, why ? and there's a better way to write this js code ? this looks not good for me.

like image 707
Victor Aurélio Avatar asked Mar 06 '26 14:03

Victor Aurélio


2 Answers

jQuery has built in functionality for replacing one element with another.

See: .replaceWith()

http://api.jquery.com/replacewith/

$("form").replaceWith(response);
like image 197
Timeout Avatar answered Mar 09 '26 08:03

Timeout


You need to use .append()/.html()

$(div).append(response);

.add() returns a new jQuery object with the current object and the objects returned by the selector passed

like image 21
Arun P Johny Avatar answered Mar 09 '26 08:03

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!