richie
richie

Reputation: 801

How can I remove the div tags from a html table using jquery or javascript?

I'm looking to remove the divs from a html table but retain the content?

<table id="datatable">
    <thead>
        <tr>
            <th></th>
            <th>Jane</th>
            <th>John</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Apples</th>
            <td><div>3</div></td>
            <td><div>4</div></td>
        </tr>
    </tbody>
</table>

I have tried:

alert($('#datatable').html().replace('<div>', ''));

But what is alerted still contains the

<div>

tags

I can't remove them from the source because they are used for other purposes.

Upvotes: 2

Views: 2062

Answers (5)

David Thomas
David Thomas

Reputation: 253318

One approach, in plain JavaScript is:

// a descriptive, but ridiculously named, function,
// htmlString: String, the string of HTML from which
//             you wish to remove certain element-types,
// toRemove: String, the element-type you wish to remove,
//           this is passed to querySelectorAll(), so a
//           CSS selector is fine, although to guard against
//           '<div>' I have removed '<' and '>' characters:
function removeElementFromHTMLString(htmlString, toRemove) {

  // here we create a <div> element:
  let div = document.createElement('div'),
  // and declare an 'empty' variable for
  // later use:
      parent;

  // here we convert the supplied selector to lower-caase,
  // and remove the '<' and '>' characters to prevent
  // errors from the user supplying '<div>', converting it
  // to 'div'; this does mean that the child combinator '>'
  // cannot be used in the selector (as currently written):
  toRemove = toRemove.toLowerCase().replace(/<|>/g,'');

  // assigning the htmlString as the innerHTML of the
  // created-<div>:
  div.innerHTML = htmlString;

  // passing the supplied selector to querySelectorAll(),
  // converting the Array-like NodeList to an Array, and
  // iterating over that Array with Array.prototype.forEach():
  Array.from(div.querySelectorAll(toRemove)).forEach(function(elem){
    // 'elem' refers to the current element in the Array of
    // elements over which we're iterating:

    // assigning the elem.parentNode to a variable for reuse:
    parent = elem.parentNode;

    // while the found element has a first child:
    while (elem.firstChild) {

      // we insert that first child ahead of the
      // current element:
      parent.insertBefore(elem.firstChild, elem);
    }

    // and then, once the element has no child
    // elements, we remove the element from its
    // parent:
    parent.removeChild(elem);
  });

  // and then, assuming you want a HTML String without
  // those elements matching the selector, we return
  // the innerHTML  to the calling context:
  return div.innerHTML;
}
    console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));

function removeElementFromHTMLString(htmlString, toRemove) {
  let div = document.createElement('div'),
    parent;

  toRemove = toRemove.toLowerCase().replace(/<|>/g, '');

  div.innerHTML = htmlString;

  Array.from(div.querySelectorAll(toRemove)).forEach(function(elem) {
    parent = elem.parentNode;
    while (elem.firstChild) {
      parent.insertBefore(elem.firstChild, elem);
    }
    parent.removeChild(elem);
  });

  return div.innerHTML;
}

console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));
td {
  color: orange;
}
td > div {
  color: limegreen;
}
<table id="datatable">
  <thead>
    <tr>
      <th></th>
      <th>Jane</th>
      <th>John</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Apples</th>
      <td>
        <div>3</div>
      </td>
      <td>
        <div>4</div>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Dev Man
Dev Man

Reputation: 2137

actually there are 3 common ways

1. Using the .html('') method

$("#my_element").html(''); // the quotes are important as just .html() returns the html DOM container within the target element

2. Using the .remove() method

$("#my_element #my_element_child").remove(); // removes the targeted child element 

3. Using the .empty() method

$("#my_element").remove(); // similar to the .html('') method it removes all children divs

Edit It seams i have made a mistake in understanding the OP's original intention as pointed out by @JosephGarrone and hence i made the following edit.

var dom = $("#my_element").html() // get the elements DOM structure
var regex = /(<div>|<\/div>)/g; // a regex to pickup the <divs in the DOM
var div_less_dom = dom.replace(regex, '') // do something with the "<div>" free DOM

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this

$('#datatable').find('div').remove();

If you want to keep content try this

$('#datatable').find('div').replaceWith(function(){
    return $(this).text()
 });

$('#datatable').find('div').replaceWith(function(){
    return $(this).text()
 });

alert($('#datatable').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
    <thead>
        <tr>
            <th></th>
            <th>Jane</th>
            <th>John</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Apples</th>
            <td><div>3</div></td>
            <td><div>4</div></td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Theodore K.
Theodore K.

Reputation: 5176

Use $('#datatable div').contents().unwrap() to remove the divs from the table and alert($('#datatable').html()) to show the remaining elements of the table.

var backup = $('#datatable').html();//Keep the html
$('#datatable div').contents().unwrap();//Remove divs
alert($('#datatable').html());//Show the table (without divs)
$('#datatable').html(backup);//Bring the old, full html back
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
    <thead>
        <tr>
            <th></th>
            <th>Jane</th>
            <th>John</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Apples</th>
            <td><div>3</div></td>
            <td><div>4</div></td>
        </tr>
    </tbody>
</table>

Upvotes: 1

JosephGarrone
JosephGarrone

Reputation: 4161

To keep the DOM unmodified (IE: Leave the <div> tags in the source) and only modify the HTML variable you can do:

var html = $('#datatable').html();
var tags = ["<div>", "</div>"];

for (var i = 0; i < tags.length; i++) {
    while (html.indexOf(tags[i]) > -1) {
        html = html.replace(tags[i], "");
    }
}

alert(html);

This is available as a demo at this fiddle.

The problem with your initial solution, is that JavaScript replace only removes the first occurrence of the specified string. Hence the while loop.

Upvotes: 1

Related Questions