[英]Remove specific inline CSS with pure JavaScript
I want to remove following inline CSS: 我想删除以下内联CSS:
<style type="text/css">.gm-style .gm-style-cc span, .gm-style .gm-style-cc a,.gm-style .gm-style-mtc div{font-size:10px}
</style>
...
With following script i try to remove the CSS, which contains '.gm': 使用以下脚本,我尝试删除包含“ .gm”的CSS:
var inline_css = document.querySelectorAll('style[innerText*=".gm"]');
if (inline_css) {
for (var i = 0; i < inline_css.length; i++) {
inline_css[i].parentNode.removeChild(inline_css[i]);
}
}
But it don't work. 但这不起作用。
Give your <style>
tag an ID, and then you'll be able to select that <style>
tag with Javascript and use the remove()
method to make it magically disappear. 给您的<style>
标记一个ID,然后您就可以使用Javascript选择该<style>
标记,并使用remove()
方法使其神奇消失。 The associated styling will also be removed. 相关的样式也将被删除。
HTML: HTML:
<style type="text/css" id="style>.gm-style .gm-style-cc span, .gm-style .gm-style-cc a,.gm-style .gm-style-mtc div{font-size:10px}
</style>
JS: JS:
var style= document.getElementById("style");
style.remove();
querySelectorAll
returns a list of elements . querySelectorAll
返回元素列表。 From those elements you can match the inner text. 从这些元素中,您可以匹配内部文本。 And if it matches your style (at all), you may remove it. 如果它完全符合您的风格,则可以将其删除。 Like so: 像这样:
var ar = document.querySelectorAll('style'); console.log("found styles: " + ar.length) for(i = 0; i < ar.length; i++){ if(ar[i].innerText.match('.gm')){ ar[i].remove() } } // to check it worked var ar = document.querySelectorAll('style'); console.log("remaining syltes: " + ar.length)
<style type="text/css">.gm-style .gm-style-cc span, .gm-style .gm-style-cc a,.gm-style .gm-style-mtc div{font-size:10px} </style> <style type="text/css">.other .style{} </style>
In case you have a few tags, you can pinpoint the exact one you need. 如果您有一些标签,则可以精确地找到所需的标签。
(() => {
'use-strict';
let needle = '.gm-style';
if ( needle === '' || needle === '{{1}}' ) {
needle = '.?';
} else if ( needle.slice(0,1) === '/' && needle.slice(-1) === '/' ) {
needle = needle.slice(1,-1);
} else {
needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
needle = new RegExp(needle);
let cssnode = () => {
let css = document.querySelectorAll('style');
for (let cs of css) {
if (cs.outerHTML.match(needle)) {
cs.remove();
}
}
};
if (document.readyState === 'interactive' || document.readyState === 'complete') {
cssnode();
} else {
addEventListener('DOMContentLoaded', cssnode);
}
})();
Has regex support too, if you need to remove multiple <style>
tags. 如果您需要删除多个<style>
标记,则也具有正则表达式支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.