tags:

views:

259

answers:

4

I have this bit of HTML code:

<center><table><tr><td>table</td></tr></table></center>

How can i unwrap table from <center>

Sorry, Im not sure even how to start.

Many Thanks

+5  A: 

I rather want to completely get rid of center tag or replace it with some div. Center tag is not wrapped in anything. Any ideas?

It's not wrapped in anything? then wrap it in something, of course!

var $center = $('center');
var $newReplacement = $("<div></div>");

$center.wrap($newReplacement);
$newReplacement.html($center.html());

Alternatively:

var $center = $("center");
$("<div></div>")
    .insertBefore($center)
    .html($center.html())
;
$center.remove();

And again, but this time without losing the events:

var $contents = $("center > *")
    .clone(true)   // not sure if this is needed
    .appendTo(
         $("<div></div>").insertBefore("center")
    )
;
$("center").remove();
nickf
I like the second one better -- but you don't need to assign the new DIV to a variable.
tvanfosson
By using html() you'll loose events etc.
svinto
+3  A: 
var $table = $("center table");
var $center = $table.parent();
$table.insertBefore($center);
$center.remove();
svinto
this solution is way faster than changing the html or cloning stuff like nickf did
Ghommey
+1  A: 

This function work just fine;

jQuery.fn.unwrap = function (el) {
    return this.each( function(){
      $(this.childNodes).appendTo(this.parentNode );
    });
};
Dom
+1  A: 

To avoid a new variable or function, I normally would "unwrap" like this:

    $("center").each(function(){
       $(this).replaceWith($(this).html());
    });

I call .each with an annonymous function to get a handle on $(this)

In your case, if you have more than one center tag on your page, you would also want to mark the one you want to remove with an id attribute and select it with something like this:

$("#zapthis").each(...
JannieT