-1

I remember from somewhere some simple way to use css code inside JS file, but can't remember how exactly.

Obviously simply putting the css code inside JS file won't work, I guess there's a need for some comments or something like that.

*Note: I don't want to use JS to render a <link...> for a css file. I want load JS file normally with <script...> and inside a *.js file I want include pure css code, as it would appear normally in *.css file.

4
  • You can add <style> tags to DOM and add styles into it? Commented Aug 2, 2016 at 10:02
  • I'm not looking for inlining css, @Arpit Goyal Commented Aug 2, 2016 at 10:05
  • You're looking for this stackoverflow.com/questions/14753147/… Commented Aug 2, 2016 at 10:08
  • Are you all skipping the *Note in the post above? Commented Aug 2, 2016 at 10:18

2 Answers 2

3
$("#id").css("parameter","property");

example..

$("#id").css("border","1px solid");

for multiple css..

$("#id").css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

better to use

addClass( )

function.. for multiple css property..

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

2 Comments

It doesn't related to the question, @Pikachu
document.write('<link href="../css/test.css" rel="stylesheet" type="text/css"></link>'); You use this line for adding whole css file using JS in *.js file.
0

Nice little function to add Internal CSS Block to document

function createStyleNode(cssText, options, doc) {
    doc = doc || document;
    var style = doc.createElement('style');
    style.type = 'text/css';
    if(options && options.id){
        style.id = options.id;
    }
    if (style.styleSheet){
        style.styleSheet.cssText = cssText;
    } else {
        style.appendChild(doc.createTextNode(cssText));
    }
    return style;
}


cssText = 'body {color: red}';
head.appendChild(createStyleNode(cssText, {'id': 'stylesFromJS'}));

Adding Ids will be useful, if you are planning to delete / replace them later from JS.

5 Comments

It doesn't related to the question, @Arpit Goyal
@uhrr please make the question a but more clear, either you want inline styles or internal styles, both answers are there, the approach can only be changed.
External styles. Inside the *.js file, @Arpit Goyal Take a look at the *Note in my post
It says: I don't want to use JS to render a <link...> for a css file. which is what external styling is. Read w3schools.com/css/css_howto.asp
Hm. What I meant is: I don't want to use JS code, to build a <link> element. If that could be confusing, the next thing isn't: I need a css code to be read from *.js file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.