Javascript将样式标记添加到头部

时间:2013-01-20 17:53:37

标签: css dom styles

我正在尝试使用javascript将一些css添加到内部样式表中。这是我用过的代码:

function googleJS(){
    var iframe = document.getElementsByTagName('iframe')[0];
    var doc = iframe.contentWindow.document;
    var newScript = doc.createElement('style');
    newScript.setAttribute('.skiptranslate { display: none; }');
    var bodyClass = doc.getElementsByTagName('head')[0];         
    bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}

然而,这导致:

<style .skiptranslate {display: none};></style> 

使用javascript在DOM中插入带有必要CSS的样式标记的正确方法是什么?

由于

2 个答案:

答案 0 :(得分:4)

顾名思义(and documentation saysElement.setAttribute

  

添加新属性或更改指定元素上现有属性的值。

这正是<style>元素上发生的事情。要解决此问题,请使用.textContent/.innerTexta text element代替.setAttribute()

function googleJS(){
    var iframe = document.getElementsByTagName('iframe')[0];
    var doc = iframe.contentWindow.document;
    var newScript = doc.createElement('style');
    var content = doc.createTextNode('.skiptranslate { display: none; }');
    newScript.appendChild(content);
    var bodyClass = doc.getElementsByTagName('head')[0];         
    bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}

答案 1 :(得分:-1)

如果你可以使用JQuery:     $()。css('Property-Name','Value');

相关问题