javascript - 如何使用 jquery 或 javascript 从 html 表中删除 div 标签?

标签 javascript jquery html replace tags

我想从 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>

标签

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

最佳答案

要保持 DOM 不变(IE:将 <div> 标签保留在源代码中)并仅修改 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循环。

关于javascript - 如何使用 jquery 或 javascript 从 html 表中删除 div 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40887728/

相关文章:

html - 圆内圆和垂直居中文本

javascript - ChartJS 后台多个图表

javascript - 从 Javascript 中的 .NET DateTime JSON 格式字符串获取正确的日期值

javascript - 如何在字段为空时使用类隐藏 DIV?

Javascript:$$ 全局变量被认为是邪恶的?

javascript - Jquery div 中的 div 中断

javascript - 返回 promise 与返回 promise 中的未定义之间的区别

javascript - 在字符串的某个位置添加冒号

jquery - 替换 DOM 元素的位置并保留其事件

javascript - JS处理 'input'按钮信息