Alexander Solonik
Alexander Solonik

Reputation: 10260

innerHTML added text to div , but content still invisible

I am loading the below function in a empty HTML document ::

setTimeout(function() {
          (function test(){
            var elem = document.createElement('div');
            body = document.body;
            body.appendChild(elem);

            var
            rule = "lalalalallalaallllllllllllllaaaaaaaaaaaaaaa" ,
            mod = 'Alex-z',
             style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join('');
             console.log(style);
            elem.innerHTML += style;
          })();
        }, 2500);

Now I have a question, no matter how big rule is, I never see any text in the browser, why ? Can somebody explain, a very similar snippet is used in a JS feature detection library, called modenizer, so I would really be interested in knowing why nothing is showing up in my browser?

Upvotes: 1

Views: 268

Answers (2)

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17481

You don't see any text in the browser because your output is:

"&#173;
<style id="sAlex-z">lalalalallalaallllllllllllllaaaaaaaaaaaaaaa</style>"
  • &#173; is the soft hyphen symbol and will be converted into the HTML name, which is &shy; and the result is not visible (http://www.ascii.cl/htmlcodes.htm)
  • The rest is just a <style> element, used only to set CSS rules and by default browser set style { display: none; }, so it's not visible.

a very similar sinppet is used in a JS feature detection library called Modernizr

Yes, Modernizr use this kind of snippets to detect some features, because in most cases needs to create an empty element and try to set the property we are trying to test. Eg:

tests['textshadow'] = function() {
        return document.createElement('div').style.textShadow === '';
    }

Upvotes: 2

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13699

Because <style></style> is by default hidden in the browser and it is set display:none if you inspect element. It's because you wouldn't want your declared styles being showed in the browsers right?

I really don't know what you're going to do, but if you want to see your styles generated on that JS then use :

div style {
  display: block;
}

Upvotes: 4

Related Questions