在JavaScript中更改outerHTML

6

$(editor[i])[0].outerHTML 的值为:

 <p style="color: red;" data-mce-style="color: red;">some string</p>

我希望data-mce-style="color: red;"消失。
我是这样做的:
$(editor[i])[0].outerHTML.replace('data-mce-style="color: red;"', '');

但它并没有替换它。

6个回答

9

.replace 创建了一个新的转换字符串,它不会改变原来的变量。你只是创建了一个新的字符串,没有将新的字符串存储回 outerHTML 中,例如:

$(editor[i])[0].outerHTML = $(editor[i])[0].outerHTML.replace('data-mce-style="color: red;"', '');

然而,这只是解决您当前问题的方法--有比将 <p> 元素转成字符串再重新解析更好的方法来实现您所需的功能。既然您正在使用jQuery,最明显的方法就是使用 removeAttr 方法:
$(editor[i]).removeAttr('data-mce-style')​;​

2

尝试:

$(editor[i]).removeAttr('data-mce-style')

当然,这将应用于选择器中的所有元素。如果您只想将其应用于第0个元素,则使用:

http://api.jquery.com/removeAttr/

$(editor[i]).first().removeAttr('data-mce-style')

1
$(editor[i]).removeAttr('data-mce-style')​;​

代码片段


1

0
尝试使用jQuery的removeData()方法:
$(editor[i]).removeData('mce-style');

0

你需要更改/删除特定的属性,为此你需要使用

$(editor[i]).removeAttr('data-mce-style');

更多信息请查看以下链接: http://api.jquery.com/removeAttr/

如果您需要更改特定属性的值,请执行以下操作:

attr(attributeName, value);

要了解更多相关信息,请查看以下链接: http://api.jquery.com/attr/


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