13

I'm trying to replace current dom element with new element i made.

I implemented following line

$(this).parent().replaceChild(newElem,this);

But it gives error saying $(this).parent().replaceChild is not a function because replaceChild is not a jQuery function, what would be equivalent in jQuery?

6 Answers 6

34

If what you want is to replace the inside:

$(this).empty().append('<p>replacement</p>')
0
16

If you want to use pure jQuery you can use the replaceWith method

$(this).replaceWith(newElem);

you can refer this link :

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

0
2

If you want to replace the elements inside the parent, do the following.

This is how to replace ALL children of an element:

$(this).children().replaceWith(<div>hello world</div>)

This is how to replace a specific child of an element by index:

$($(this).children()[3]).replaceWith(<div>hello world</div>)
1

You can try this

$(this).parent().get().replaceChild(newElem,this);

If $(this).parent() is unique on the page. (.get() gives you the DOM object)

If you want to use pure jQuery you can use the replaceWith method

$(this).replaceWith(newElem);
2
  • it replaces parent element.
    – Rameez
    Sep 13, 2013 at 4:46
  • If you only want to replace the current element .. Remove .parent Sep 13, 2013 at 4:48
0

Try replacewith()

$(this).parent().replaceWith(newElem);
1
  • it replaces parent element.
    – Rameez
    Sep 13, 2013 at 4:47
0

For anyone looking for a vanilla JS approach, use replaceWith:

this.replaceWith(newElem);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.