Awais Imran
Awais Imran

Reputation: 1344

Remove TABLE, TR, TD tags through jquery

Is it possible to remove "TABLE, TR, TD" tags through jquery but content shouldn't be deleted inside the table.

i.e. Below is my table code contained images and I want to remove only table, tbody, tr and td tags around the images.

Code before jquery

<div id="Gallery">
    <table>
      <tbody>
        <tr>
            <td><img src="image1.jpg"></td>
        </tr>
        <tr>
            <td><img src="image2.jpg"></td>
        </tr>
        <tr>
            <td><img src="image3.jpg"></td>
        </tr>
      </tbody>
    </table>
</div>

Code should be after jquery

<div id="Gallery">
    <img src="image1.jpg">
    <img src="image2.jpg">
    <img src="image3.jpg">
</div>

Thanks in advance!

Upvotes: 1

Views: 8590

Answers (8)

Adil Shaikh
Adil Shaikh

Reputation: 44740

Working Fiddle

var img = "";
$("td").each(function(){
  img = img + $(this).html();
});

$("#Gallery").append(img);
$("table").remove();

Upvotes: 0

cockypup
cockypup

Reputation: 1043

Here it is

var list = $('#Gallery table td *');
$('#Gallery').html(list.get());

You can play with it in here: http://jsfiddle.net/cockypup/Dehgf/2/

The CSS is just to make evident the table is disapearing.

Upvotes: 0

Ejaz
Ejaz

Reputation: 8872

Another way of doing it

        var gallery = $("#Gallery");
        var imgs = $("img", gallery).clone();

        $("table", gallery).remove();
        gallery.append(imgs);

the selector is optimized and the imgs variable still has a reference to the images inserted in #Gallery

Upvotes: 0

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

$("#Gallery img").each(function(){
    $("#Gallery").append($(this));
});
$("#Gallery table").remove();

http://jsfiddle.net/hescano/jGT5b/

Upvotes: 2

user835223
user835223

Reputation:

If you are solely expecting content within the <td> elements as you should be, you can use the following:

 $(function(){
    var g = $('#Gallery'),
    f = '';

    $('td', g).each(function(){
        f += $(this).html();
    });

    g.html(f);

});

Upvotes: 0

Ian
Ian

Reputation: 50905

Try:

var gallery = $("#Gallery");
var contents = gallery.find("td, th").contents().detach();
gallery.find("table").remove();
gallery.append(contents);

DEMO: http://jsfiddle.net/Ydsg9/

Upvotes: 3

Ram
Ram

Reputation: 144689

$('#Gallery table').replaceWith(function(){
     return $(this).find('td *');
});

http://jsfiddle.net/ec46T/

Upvotes: 2

palaѕн
palaѕн

Reputation: 73906

Try this:

$('#Gallery img').unwrap().unwrap().unwrap().unwrap();

Upvotes: 0

Related Questions