Mohit Mohit - 1 year ago 99
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


and it will create


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> {
text-align: center;
color: red;

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

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

Answer Source

You can simply use jquery .text method like

const cssCode = ` {
    text-align: center;
    color: red;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download