开发者

javascript element.style is undefined in FF

I want to set up css display property in javascript code:

    var div = document.createElement('div');
    div.innerHTML = content;
    div.chil开发者_运维问答dNodes[0].style.display = '';

It works in IE but doesn't in FF. It says "style" is undefined for element div. How can I do it in FF?

Thanks


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

You can either:

  • loop over the children until you either get to the end or find an HTMLElementNode
  • strip the whitespace from the start of content
  • switch to using createElement and friends instead of innerHTML


This should also work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜