0

I want to convert the source of the website inside a String variable to code and use it.

How can I do this?

var cssStr = 'a{text-decoration: none}';

// to css code

a {
   text-decoration: none
}
1

4 Answers 4

0

Try this:

var cssStr = 'a{text-decoration: none} a{color: red}';

let text = document.getElementById('yourId');
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = cssStr;
text.appendChild(style);
<a href=# id="yourId"><p> Your Text </p></a>

Sign up to request clarification or add additional context in comments.

Comments

0

You can have below script:

var cssStr = 'a{text-decoration: none}';
let styleTag = document.createElement('style');
styleTag.innerHTML = cssStr;
document.firstChild.appendChild(styleTag);

This will basically create <style></style> and append it to html. If you have specific <style> tag, select it instead of creating new.

Comments

0
var element = document.getElementById("myDIV");
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { text-decoration: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

element.className = 'cssClass';

Comments

0

This is what CSSStyleSheet.insertRule is for:

let styleSheet = document.styleSheets[0];
styleSheet.insertRule('.demo { background: red; color: white; }');
<div class="demo">test</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.