4

chaning xml attributes through jquery is easy-peasy, just:

$(this).attr('name', 'hello');

but how can I add another tag into the file? I tried using append the JS dies silently.

Is there any way to do this?

Clarifications: this code is part of an extension to firefox, so don't worry about saving into the user file system. Still append doesn't work for xml documents yet I can change xml attribute values

0

2 Answers 2

10

The problem is that jQuery is creating the new node in the current document of the web page, so in result the node can't be appended to a different XML Document. So the node must be created in the XML Document.

You can do this like so

var xml = $('<?xml version="1.0"?><foo><bar></bar><bar></bar></foo>'); // Your xml
var xmlCont = $('<xml>'); // You create a XML container
xmlCont.append(xml); // You append your XML to the Container created in the main document

// Now you can append without problems to you xml
xmlCont.find('foo bar:first').append('<div />');

xmlCont.find('foo bar div'); // Test so you can see it works
2
  • 1
    This works nicely in FF & Chrome, but IE does not like it much. The problem is that it cannot parse the initial XML string in the first expression. Even if you do handle the IE specific parsing, having your XML document wrapped in a jQuery object does not allow you to append it to the <xml> node as show above. The 'html' method also does not work, one need to use 'innerHTML' and give it the initial XML string as its value. Trying to find nodes in the <XML> node will also not work. You will have to use $("foo bar:first", xmlDoc) to provide some context for jQuery.
    – NeilC
    Jun 18, 2010 at 9:19
  • 1
    @Raybiez is correct about IE- however as of jQuery 1.5 you should be able to use .parseXML(...) to resolve this issue (Haven't tested): api.jquery.com/jQuery.parseXML
    – Yarin
    Jun 29, 2011 at 11:38
1

I'd suggest you walk through the code with a debugger and see if you can determine why the append is causing an error (or if the error is someplace else). Something like:

$('selector').append('<p></p>');

should work just fine.

2
  • Have you tried the related manipulators like prepend() and insertAfter()?
    – acrosman
    Jul 6, 2009 at 13:46
  • I can confirm this dies silently
    – Yarin
    Jun 29, 2011 at 11:32

Your Answer

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

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