Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceWith on XML problem

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

I have found this admittedly simple workaround, in case anybody needs it in the future, that 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's 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 shouldn't this 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 function version of replaceWith, like so:

$(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 however, but I need to use the function version so I can't settle for 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
like image 521
Seth Carnegie Avatar asked Jul 09 '11 03:07

Seth Carnegie


1 Answers

This looks like either a design limitation with replaceWith() or a bug.

When I run:

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

I get a "this[0].innerHTML is undefined" exception. See this jsFiddle.

Drilling into xml, the b node doesn't have an innerHTML member -- which makes a little sense, since it's not HTML. ;)

So, it's looking like replaceWith() may not always play nice with XML. Consider reporting a bug.

like image 149
Brock Adams Avatar answered Oct 25 '22 06:10

Brock Adams