最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - javascript element.style is undefined in FF - Stack Overflow

programmeradmin5浏览0评论

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

    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[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

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

    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[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

Share Improve this question edited Dec 20, 2010 at 17:41 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Dec 20, 2010 at 17:38 ihorkoihorko 6,95526 gold badges80 silver badges123 bronze badges 1
  • 1 What kind of node is div.childNodes[0]? – Pointy Commented Dec 20, 2010 at 17:40
Add a ment  | 

2 Answers 2

Reset to default 5

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)

  1. 暂无评论