tags:

views:

82

answers:

2

hi,

I want to replace tag with tag, but not replacing all the children elements (just the parent). How to do it with jQuery ?

thanks

+4  A: 
var elToRemove = $('your-element');
var children = elToRemove.children().detach();

elToRemove.replaceWith('<whatever id="something">Foo Bar</whatever>').append(children);

Note that this actually removes the parent element, and inserts a new one, so all details such as event handlers and data will be lost on the parent, but is preserved on the children.

Matt
ok thanks, however it gives me this error: "elToRemove.children().detach is not a function". (See comment below also).
Patrick
What version of jQuery are you running? detach was introduced in 1.4, as was unwrap, so my guess is you're using an out of date version.
Matt
yeah.. indeed 1.2.6 I'm using Drupal and this is the built-in jQuery. I dunno if I can update it without having problems in other part of Drupal code
Patrick
Jesus christ, I doubt half of us was even born when 1.2.6 was around. jQuery is usually pretty good as far as backwards compatibility is concerned, but yeah. 1.2.6 is oooooooold. You could run 2 versions of jQuery simultaneously using the noConflict option if you did so desired.
Matt
uhm, it seems that Drupal is not compatible with newest versions of jQuery. I get an error. Is there any other way to write the code above ? Maybe with inject append ?
Patrick
I actually only need to use something else instead of detach. Just a small change...
Patrick
If you used `.remove` as an alternative, bear in mind that any events handlers will be lost.
Matt
+2  A: 

I'm not sure I entirely understand the question, but perhaps this is the answer? ;-)

$('#replaceme').children().unwrap().wrap('<div id="new"></div>');

See it in action: http://jsbin.com/adene3/edit

Doc:

Kyle Mitchell
same here: "$("a.taxonomy-image-link-alter").children().unwrap is not a function". I'm sure jQuery works. I'm using it with other plugins.
Patrick
The doc for unwrap() above lists "version added: 1.4". The jsbin demo also uses 1.4. Which version are you running?
Kyle Mitchell