Javascript element.style undefined in FF

I want to set the CSS display property in javascript code:

    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[0].style.display = '';

It works in IE, but not in FF. It says the "style" is undefined for the div element. How can I do this in FF?

thank

+3
source share
2 answers

What is content? If it starts with a space, then the TextNode will be the first child and they don't have style properties (HTMLElementNodes do).

You can:

  • loop over children until you reach the end or find an HTMLElementNode
  • separate the spaces from the beginning content
  • switch to use createElementand friends insteadinnerHTML
+5
source

This should also work:

var div = document.createElement('div');
div.innerHTML = content;
div.childElementCount && div.firstElementChild.style.display = '';
0

Source: https://habr.com/ru/post/1781283/


All Articles