Mohit Mohit - 4 months ago 12
jQuery Question

Can we Create CSS Selector rule with JQuery or Javascript?

we can create style or any other tag with

var st = document.createElement("style");


and even append the same to body

body.append(st);


and it will create

<body><style></style></body>


I wanna know can we put style in style tag with javascript as well not simple rules, I know there is $("selector").css() function is there which can apply css rules to selector but i want a bit more powerful rule and I want to add in style tag i just created,

something like this:

<style>
div.bar {
text-align: center;
color: red;
}
</style>


st.innerHtml or st.innerText are not letting me set these values.


Note: This was asked me to do in Browser Console only.

Answer

You can simply use jquery .text method like

const cssCode = `div.bar {
    text-align: center;
    color: red;
}`
$('style-tag-selector').text(cssCode)

but in my opinion, whetever your goal is - this solution is not ok. You shouldn't mess with CSS via JavaScript.

Best approach is to have styles in separately loaded .css file and then you can toggle classes to elements with javascript.