Chris Wallace
Chris Wallace

Reputation: 515

JQuery replaceWith problem

I'm replacing a DOM node with HTML returned from an AJAX call. The returned HTML has an id and the DOM node with that id is to be replaced.

The callback function

function updateTrip(xml, success, jqXHR) {
  var para = $(xml);  
  var id = para.attr('id');
  $("#"+id).replaceWith(para);  
}

fails to replace the node although the same code with a fixed id works, and the equivalent raw JavaScript function also works

function updateTrip(xml, success, jqXHR) {
  var para = $(xml).get(0);  
  var id = para.getAttribute('id');
  var div = document.getElementById(id);
  div.parentNode.replaceChild(para, div);   

}

The ids look like n-1.12.2.2.4 ; the content-type is text/html; no errors reported in the FF error console.

Upvotes: 0

Views: 1790

Answers (1)

Mark Coleman
Mark Coleman

Reputation: 40863

The issue is with the . in your id, you need to escape the . for the selector to work correctly.

Example:

$("#n-1\\.12\\.2\\.2\\.4")

With that being said, the easiest option would be to use document.getElementById() and simply use .replaceWith()

function updateTrip(xml, success, jqXHR) {
  var para = $(xml);  
  var id = para.attr('id');
  var a = document.getElementById(id);
  $(a).replaceWith(para);  
}

Example on jsfiddle

or if you want to do the replace() option it would look like this:

function updateTrip(xml, success, jqXHR) {
    var para = $(xml);
    var id = para.attr('id').replace(/\./g, '\\.');
    $('#' + id).replaceWith(para);
}

Example on jsfiddle

Upvotes: 2

Related Questions