2017-10-09 47 views
1

刪除特定的內聯CSS我想刪除以下內嵌CSS:與純JavaScript

<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> 
... 

有了下面的腳本我嘗試刪除CSS,其中包含 '.gm':

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]); 
    } 
} 

但它不起作用。

+1

不能從樣式表中刪除css。它不這樣工作。 – Amy

回答

1

querySelectorAll返回elements列表。從這些元素你可以匹配內部文本。如果它符合你的風格(根本),你可以刪除它。像這樣:

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>

如果你有一些標籤,你可以找出你所需要的確切之一。

1

給你<style>標籤的ID,然後你就可以選擇<style>標籤使用JavaScript和使用remove()方法,使其神奇地消失。關聯的樣式也將被刪除。

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:

var style= document.getElementById("style"); 
style.remove(); 
+0

我沒有提到。 Google提供的「.gm」類有多種內聯樣式,因此我無法向其添加id屬性。 – Prolativ