javascript - 使用 javascript/jquery 从字符串元素中删除内联样式

标签 javascript jquery html regex

假设我有这个字符串:

let string = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>';

所以基本上它是一堆像这样但在字符串中的元素:

<h1 style="bunch of class"> </h1>
<h2> 
  <p style="bunch of class"> </p>
  <p style="bunch of class"> </p>
</h2>

使用 jquery 或 vanilla javascript,如何从字符串中删除样式属性?

这个我已经试过了:

$(string).find('h1').removeAttr('style');

但是没有效果

最佳答案

这里有两个潜在的问题。首先,您需要从 string 创建一个 jQuery 对象并保存对它的引用。如果不这样做,您将丢失对 HTML 所做的更改。

其次,您需要使用 filter() 而不是 find(),因为没有单一的根级别 在 HTML 字符串中搜索的节点。试试这个:

let string = '<h1 style="color: red;">H1 Foo</h1><h2 style="color: yellow;">H2 Foo<p style="color: green;">P Foo</p><p style="color: blue;">P Foo</p></h2>';

let $string = $(string);
$string.filter('h1').removeAttr('style');
$('body').append($string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - 使用 javascript/jquery 从字符串元素中删除内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501936/

相关文章:

javascript - Promise/A+ 规范的哪一部分要求 Promise 必须从返回的 Promise 吸收状态?

javascript - jQuery Datepicker 不会改变输入值

html - 区分CSS中的字体字体

javascript - 日程应用程序上的无限时间轴

html - Bootstrap 搜索栏 - 如何删除 bootstrap 网格中表单元素之间的空格

javascript - 检测背景图片属性,检测背景图片比例,添加相关类

javascript - 整数对语法

javascript - jQuery 数据表中的下拉过滤

javascript - 如何用 Formik 和 React 实现可添加字段?

javascript - 使用 jquery 更改选择框中的默认文本