假设我有这个字符串:
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/