-1

I need to remove a single tag from the DOM using jQuery or JavaScript. I only need to remove the enclosing tag, not the content inside the tag.

remove(), detach(), empty() methods cannot be applied as they remove the whole content as well.

for example:

<table border="1" style="width:300px">
<tr>
  <td>Jill</td>
  <td>Smith</td> 
  <td>50</td>
</tr>
<tr>
  <td>Eve</td>
  <td>Jackson</td> 
  <td>94</td>
</tr>
</table>

need to remove only the <table></table>.

Currently DOM looks like this

<table style="width:600px">
<tbody><p> Number  -  Name  -   <br></p>
    <p> 111  -  ABC  -  <br></p>
    <p> 222  -  KLM  -  <br></p>
    <p> 333  -  NOP  - <br></p>
    <p> 444  -  HIJ  -  <br></p>
</tbody></table>

Thank you in advance.

6
  • 7
    If you removed the table element and left the table row elements behind then the document would be invalid. Why would you want that?
    – Quentin
    May 28, 2014 at 13:47
  • I agree with @Quentin. You shouldn't do it, but for this specific example, you could do something like var table = document.querySelector("table"); table.outerHTML = table.innerHTML;
    – ndugger
    May 28, 2014 at 13:49
  • No all these table data needs to be represented in paragraphs. Now I get the paragraphs inside a cage. I want to remove that. for that I need to remove the table tag as well. <th> <td> all are removed in the DOM. May 28, 2014 at 13:50
  • 3
    What does the HTML look like now and what do you want it to look like?
    – putvande
    May 28, 2014 at 13:52
  • @user3547920 if you're counting on the <tr> and <td> being removed as well, how about using the .text() method to extract the text and then replace in a paragraph? Is that the intent? It would be useful if you included what your desired resulting DOM would be.
    – artlung
    May 28, 2014 at 13:52

4 Answers 4

5

Try to .unwrap() it, but the result would be an invalid html,

$('tr').unwrap();
1
var text=$("table").text();
$("table").parent().html(text);// now at the place of text come 
1
$("table").replaceWith($("table").html());
1

With Jquery :

$('table').each(function(){
    $(this).replaceWith($(this).html());
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.