replaceWith on XML problem
Asked Answered
T

2

6

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
Tamartamara answered 9/7, 2011 at 3:14 Comment(0)
J
2

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.

Jeth answered 9/7, 2011 at 4:26 Comment(4)
Would you consider this worth reporting?Tamartamara
@Seth: Sure, why not? The worst that can happen is that you'll get a "won't fix" and at least the issue will be documented.Scrutiny
Yes. It doesn't work as reasonable people would expect, or as the documentation implies. Just search for prior bugs before posting (I did a quick search and didn't see anything).Jeth
@mu is too short: No the worst that could happen is... "You are a blithering idiot; here's proof." :) I've been called worse.Jeth
H
0

yes. this is old bug and it still exists. you can workaround it:

$.ajax
  dataType: "xml"
  ...
  success:  (data) ->
    $(data).find("section").each ->
      ugly_but_working_clone = $($(".existing_dom_element").append(this).html())
Hygroscopic answered 21/5, 2012 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.