2

I realise this is similar to Using jQuery to replace one tag with another, however I'm looking to replace a tag with another tag inside html, but KEEP the attributes and any defined custom data (set via $.data) for the object. Any idea how to achieve this?

Community
  • 1
  • 1
frumbert
  • 2,323
  • 5
  • 30
  • 61
  • possible duplicate of [Change the tag but keep the attributes and content -- jQuery/Javascript](http://stackoverflow.com/questions/3665820/change-the-tag-but-keep-the-attributes-and-content-jquery-javascript) – Explosion Pills Dec 14 '12 at 02:07
  • Why do you want to do this? Which tags concretely? Why don't you edit the HTML source instead? I'm asking because what you want seems like an awful approach. – Šime Vidas Dec 14 '12 at 02:09
  • where is your sample html? – charlietfl Dec 14 '12 at 02:14
  • @Explosion Pills - That other question is not a duplicate, because it doesn't cover keeping values stored with `.data()`. frumbert - do you also want to keep event handlers? – nnnnnn Dec 14 '12 at 02:26

1 Answers1

0

Copying the attributes shouldn't be too hard, this answer focuses on retaining the data and events that are attached to a node.

When you write $('#myid').data('msg', 'hello world'), internally jQuery creates a special property onto the DOM element called jQuery.expando (which is just a string that starts with "jQuery" and followed by a bunch of numbers). The value of that property holds a key to the jQuery.cache array, which is where your custom data and event handlers are stored in.

// lets assume you want to replace node a with node b
// we need the DOM elements for this
var nodea = ..., nodeb = ...;

// jQuery data references are stored in a special property of the node
var key = nodea[jQuery.expando], 
cache = jQuery.cache[key];

// perform replacement
$(nodea).replaceWith(nodeb);

if (cache) {
  // restore data
  jQuery.cache[key] = cache;
  nodeb[jQuery.expando] = key;
}

Demo

You should use this at your own risk though; messing with internals is often not the best solution.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309