【问题标题】:How can I remove the div tags from a html table using jquery or javascript?如何使用 jquery 或 javascript 从 html 表中删除 div 标签?
【发布时间】:2016-11-30 11:55:03
【问题描述】:

我希望从 html 表格中删除 div 但保留内容?

<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>

我试过了:

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

但是警告的内容仍然包含

<div>

标签

我无法从源中删除它们,因为它们用于其他目的。

【问题讨论】:

  • 您想删除div-标签吗?并让每个td 取而代之的是div 标签的内容?

标签: javascript jquery html replace tags


【解决方案1】:

要保持 DOM 不被修改(即:将 &lt;div&gt; 标记留在源代码中)并且只修改 HTML 变量,您可以这样做:

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 fiddle 获得。

您最初解决方案的问题在于 JavaScript replace 仅删除了指定字符串的第一次出现。因此while 循环。

【讨论】:

  • @richie 这能满足你的需要吗?
【解决方案2】:

使用$('#datatable div').contents().unwrap() 删除表格中的divs,使用alert($('#datatable').html()) 显示表格的其余元素。

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>

【讨论】:

  • 问题表明 OP 不希望修改源代码。
  • 根据代码sn-p,仍然删除了div。
  • @我明白了......所以我再次更新了我的解决方案,也许删除了 div,显示警报并再次将它们带回来按 OP 的意愿工作。
【解决方案3】:

试试这个

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

如果你想保留内容试试这个

$('#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>

【讨论】:

  • 不幸的是,这也删除了内容。我需要标签去,但内容要留下
  • 片段仍在删除div。 OP 试图保持源不受影响,并且只修改代码中的字符串,而这些影响不会到达 DOM。
【解决方案4】:

其实有3种常用方式

1.使用.html('')方法

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

2.使用.remove()方法

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

3.使用.empty()方法

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

编辑正如@JosephGarrone 指出的那样,我在理解 OP 的初衷时犯了一个错误,因此我进行了以下编辑。

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

【讨论】:

  • 问题表明 OP 不希望修改源代码。
  • @JosephGarrone 我以为他想使用 jquery 动态修改它
  • 查看问题的最后一行“我无法从源中删除它们,因为它们用于其他目的。”
  • “我无法从源中删除它们,因为它们用于其他目的。”我以为他的意思是在 SOURCE 源代码中,会更新答案
【解决方案5】:

一种方法,在纯 JavaScript 中是:

// 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>

【讨论】:

  • 这似乎从 DOM 中删除了 div 标记 - 基于代码和 sn-p 的执行结果。 OP 已经声明他不能修改 DOM。
  • @Joseph:再检查一遍?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
相关资源
最近更新 更多