I am reading in an XML document and would like to find the first tag of a specific name, and replace that instance with a different tag and contents. I am using find and first, but the replaceWith call is not replacing it.
$(storyXML).find('oldTag').first().replaceWith('<newTag>text</newTag>') ;
});
The find is finding multiple oldTags, the first is returning the first of them, the replaceWith is doing nothing. After searching around Stack Overflow, I even tried replacing all of them using:
$(storyXML).find('oldTag').each(function() {
$(this).replaceWith('<newTag>text</newTag>') ;
});
But that didn't do anything either. I appreciate any help you can offer!
EDIT: storyXML is being assigned here (tried to simplify the code for posting, hopefully it still makes sense):
var load = function () {
var fn;
fn = function (obj, init) {
storyXML = obj.responseXML;
};
ajax("GET", this.url, null, fn);
};
EDIT 2: Fixed code via Jason's answer below. Posting for anyone else having this issue and lost finding a workaround like I was.
var xmlDoc = $.parseXML( storyXML );
var $xml = $( xmlDoc );
$xml.find('oldTag').first().replaceWith('<newTag>stuff</newTag>');
// if you want to keep the old XML string updated, need to do this step
storyXML = (new XMLSerializer()).serializeToString(xmlDoc);
Have you tried https://api.jquery.com/jQuery.parseXML/ ? Sometimes jQuery will operate on either strings or DOM objects, but other times jQuery expects objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With