简体   繁体   中英

Internal CSS injected by JavaScript is not applying

I'm adding a div into my webpage using JavaScript and along with that div I'm adding a bit of CSS code so the code looks like this

   <script>
var rand= randomString();
    var html = '<div class="'+rand+'">Welcome to StackOverflow!</div>
    <style>.'+rand+'{color:red}</style>';

    document.getElementById("parent_div").innerHTML = html;

function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 18;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return  randomstring;
}
    </script>

This is working most of the time, and for some reason this CSS is not applying to this div , but CSS is injected along with the HTML. I also changed the order, added CSS first and then HTML but no luck, failing only few times despite same code working most of the time.

CSS will not be applied if it is not in the head unless it is using the scoped attribute and the style tag is inside the element it will be applied to.

This should work for you:

<script>
var html = '<div class="rule"><style scoped>.rule{color:red}</style>Welcome to StackOverflow!</div>';

document.getElementById("parent_div").innerHTML = html;
</script>

If you want more info on how this works, here's a good article for you: http://html5doctor.com/the-scoped-attribute/

Instead of adding stylesheets like that, try this:

document.styleSheets[0].addRule('.rule','color: red;');
var html = '<div class="rule">Welcome to StackOverflow!</div>';
document.getElementById("parent_div").innerHTML(html);
document.getElementById("parent_div").innerHTML = html

You need to set css this way.

Check this https://jsfiddle.net/3xs1bsrp/1/

I found the bug in my program, I was using a random string generator for class and when the random string first character was number it failed when it started with a character it worked

.3as324sdfsr4 => faield

.wer6sdf74hjg => worked

so I added a character in front of return string to solve this

function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 18;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return  's'+randomstring;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM