0

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.

Amokrane Chentir
  • 29,907
  • 37
  • 114
  • 158
Chris Wallace
  • 495
  • 3
  • 11

1 Answers1

2

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

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
  • It's advisable to steer clear of periods in IDs, even though they are permitted, it causes havoc in sizzle and other selector libraries. [This post explains nicely.](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html/72577#72577) – Orbling May 11 '11 at 22:57
  • Thanks both for the answers - the more minimal javascript version works fine but I'll have to consider recoding ids – Chris Wallace May 12 '11 at 06:37