2

I'm trying to add some css to an internal stylesheet with javascript. This is the code I've used:

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

However this results in:

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

What is the proper method to use javascript to insert a style tag with the necessary CSS inside the DOM?

Thanks

1
  • as the function name suggests, setAttribute() sets "attributes" for elements. And that's what exactly happens with your code. Commented Jan 20, 2013 at 17:55

2 Answers 2

5

As the name implies (and documentation says) Element.setAttribute:

Adds a new attribute or changes the value of an existing attribute on the specified element.

which is exactly what's happening on the <style> element. To fix this, use .textContent/.innerText or a text element instead of .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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

@user208709 you're welcome, but it's really just a matter of reading the docs :)
Btw, is it possible to add multiple CSS attributes in the createTextNode?
Yes, it is. Why don't you just experiment with it? And, like I said, read the docs. There are rich, well-documented APIs for manipulating CSS rules. Go explore! developer.mozilla.org/en-US/docs/DOM/HTMLStyleElement
Sorry if I sound lazy, I'm not. I'm just working on a tight schedule and the other members have left the team so I'm working on several solutions all at once and it's just this part that I couldn't find a quick solution.
-1

If you can use JQuery: $().css('Property-Name', 'Value');

2 Comments

Who said anything about jQuery? Also, this is not even equivalent to what the OP is trying to do.
.css() is still not directly equivalent to inserting a new CSS rule.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.