ReplaceWith on XML issue

After examining the jQuery source, I see that the problem I am facing is that replaceWith calls html , which does not exist for XML documents. Is replaceWith supposed to work with XML documents?

I found this admittedly a simple workaround, in case someone needs it in the future, this will accomplish what I'm trying to do:

 xml.find('b').each(function() { $(this).replaceWith($('<c>yo</c>')) // this way you can custom taylor the XML based on each node attributes and such }); 

But I would still like to know why the easy way doesn't work.


I don't know much about jQuery, but should this not work?

 xml = $.parseXML('<a><b>hey</b></a>') $(xml).find('b').replaceWith('<c>yo</c>') 

Instead of xml representing <a><c>yo</c></a> , it fails and represents <a></a> . Did I do something wrong? I am using jQuery 1.6.2.

Edit:

As a side note, if I try to use the version of the replaceWith function, like this:

 $(xml).find('b').replaceWith(function() { return '<c>yo</c>' // doesn't matter what I return here }) 

I get this error:

 TypeError: Cannot call method 'replace' of undefined 

Edit 2:

replaceAll works, but I need to use the version of the function, so I cannot agree to this:

 $('<c>yo</c>').replaceAll($(xml).find('b')) // works 

Edit 3:

This also works:

 xml.find('b').replaceWith($('<c>yo</c>')) // but not with the $() around the argument 
+6
source share
2 answers

It looks like a design restriction with replaceWith() or an error.

When I run:

 $(xml).find('b').replaceWith(function() { return '<c>yo</c>'; }) 

I get the exception "this[0].innerHTML is undefined" . Check out this jsFiddle .

Having drilled into xml , the b node has no innerHTML member, which makes little sense since it is not HTML .;)

So it looks like replaceWith() , maybe it doesn't always mix well with XML. View the error report .

+2
source

Yes. this is an old mistake, and it still exists. you can get around this:

 $.ajax dataType: "xml" ... success: (data) -> $(data).find("section").each -> ugly_but_working_clone = $($(".existing_dom_element").append(this).html()) 
0
source

Source: https://habr.com/ru/post/892376/


All Articles