使用JavaScript/jQuery从字符串元素中删除内联样式

3

假设我有这个字符串:

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 或纯 JavaScript,我该如何从字符串中删除样式属性?
我已经尝试过这个方法:
$(string).find('h1').removeAttr('style');

但是它没有起作用。

您需要删除所有样式还是仅限于 h1 样式? - Kosh
@KoshVery 所有元素的所有样式。基本上我想要的是所有元素的原始版本,没有任何属性或样式,只有纯骨架。 - Daniel
我已经更新了我的答案,以帮助您去除任何属性。 - Kosh
5个回答

3

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

其次,由于HTML字符串中没有单个根级节点进行搜索,因此您需要使用filter()而不是find()。尝试这样做:

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>


我喜欢“secondly”。没有意识到可以这样过滤。 - Jai
你的回答太棒了,我差不多快做到了。再问一个问题,如何删除h2元素内p元素的样式?我尝试过使用$string.filter('h2 p').removeAttr('style');但没有起作用。 - Daniel
1
你需要使用 filter() 方法来获取 h2,然后在其中使用 find() 方法来获取 p$string.filter('h2').find('p').removeAttr('style'); - Rory McCrossan

2
您可以在代码中创建一个虚拟元素并将内容放入其中。然后找到该元素并删除属性:

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

let $div = $('<div>')
$div.html(str).find('h1').removeAttr('style');

$(document.body).append($div.html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


2
我们可以通过正则表达式实现这一点。
const string = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>';
const stringNoStyle = string.replace(/style="(.*?)" /g, '')
// <h1> </h1>
// <h2>
//    <p> </p>
//    <p> </p>
// </h2>

1
如果您需要从字符串中删除所有样式,可以按照以下方式进行:

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

$('<div>' + string + '</div>')
  .find('[style]').attr('style', null)
  .appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

更新
为了给您提供真正想要的内容,我编写了以下jQuery扩展程序。
它会从html片段中删除所有属性,除了您想要保留的属性。
可应用于jQuery对象。
接受一个要保留的属性数组(可选)。
返回类似于jQuery html() 方法的html字符串。

$.fn.extend({
  stripHTML: function(keep = []) {        
    return $('<div>')
      .append(this)
      .find('*').each(function(i, e) {
        for (var {name} of [...e.attributes]) {
          if (!keep.includes(name)) e.removeAttribute(name);
        }
      })
      .end()
      .html();
  }
});

let string = '<h1 Title="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 <a href="foo">Foo</a></p></h2>';

let keep = ['href', 'name', 'value']; // attrs to keep

let stripped = $(string).stripHTML(keep);

$('body').html(stripped);

console.log(stripped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


这是我接受的答案,因为这正是我所需的: 删除所有元素及其子元素上的所有样式。但是,如果其他人遇到此问题,@Rory McCrossan的答案也有效,但您必须从其父级过滤所有其他子元素。 - Daniel
@Daniel 如果你想使用这个逻辑,我强烈建议避免使用 * 选择器,因为它会使速度变慢。请改用 [style] - Rory McCrossan
1
@RoryMcCrossan,非常棒的改进!谢谢,我已经更新了答案。 - Kosh

0
创建一个 div 并将字符串插入到它的 innerHTML 中。然后选择 h1 并从中删除 style

var string = '<h1 style="color:red">h1</h1><h2 style="color:red">h2</h2>';
var div = document.createElement("div");
div.innerHTML = string;
div.querySelector("h1").removeAttribute("style");
document.body.append(div) 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接