javascript 删除页面中所有样式的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9252839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:04:48  来源:igfitidea点击:

simplest way to remove all the styles in a page

javascriptjquerystyles

提问by tic

I need to remove all the style definitions in a page using javascript, to obtain the same result as doing View > Page Style > No Stylein Firefox. Which is the simplest way?

我需要使用 javascript 删除页面中的所有样式定义,以获得与View > Page Style > No Style在 Firefox 中相同的结果。哪种方法最简单?

回答by xandercoded

You can recursively iteratethrough all elements and remove the styleattribute:

您可以递归遍历所有元素并删除style属性:

function removeStyles(el) {
    el.removeAttribute('style');

    if(el.childNodes.length > 0) {
        for(var child in el.childNodes) {
            /* filter element nodes only */
            if(el.childNodes[child].nodeType == 1)
                removeStyles(el.childNodes[child]);
        }
    }
}

removeStyles(document.body);

To remove linked stylesheets you can, in addition, use the following snippet:

要删除链接的样式表,您还可以使用以下代码段:

var stylesheets = document.getElementsByTagName('link'), i, sheet;

for(i in stylesheets) {
    sheet = stylesheets[i];

    if(sheet.getAttribute('type').toLowerCase() == 'text/css')
        sheet.parentNode.removeChild(sheet);
}

回答by Joe

If you have jQuery, you can probably do something like

如果你有 jQuery,你可能可以做类似的事情

$('link[rel="stylesheet"], style').remove();
$('*').removeAttr('style');

回答by Rajkeshwar Prasad

Here is the ES6 goodness you can do with just one line.

这是您可以用一行代码实现的 ES6 优点。

1) To remove all inline styles (eg: style="widh:100px")

1)要删除所有内嵌样式(如:style="widh:100px"

document.querySelectorAll('[style]')
  .forEach(el => el.removeAttribute('style'));

2) To remove link external stylesheet (eg: <link rel="stylesheet")

2)为了除去链路外部样式表(例如:<link rel="stylesheet"

document.querySelectorAll('link[rel="stylesheet"]')
  .forEach(el => el.parentNode.removeChild(el));

3) To remove all inline style tags (eg: <style></style>)

3)要删除所有内嵌样式标签(例如:<style></style>

document.querySelectorAll('style')
  .forEach(el => el.parentNode.removeChild(el));

回答by Londeren

Actually, document.querySelectorAllreturns NodeListwhich has forEachmethod.

实际上,document.querySelectorAll返回NodeList具有forEach方法的。

document.querySelectorAll('link[rel="stylesheet"], style')
  .forEach(elem => elem.parentNode.removeChild(elem));