element.firstChild is returning '<TextNode …' instead of an Object in FF

后端 未结 6 1993
傲寒
傲寒 2020-11-29 07:50

I wrote a tab system using some very basic Javascript and it runs like a champ in IE 8 but, in FireFox 3 I am coming up short. The pertitent HTML is as follows:

<         


        
相关标签:
6条回答
  • 2020-11-29 08:02

    You can try

    document.getElementById(TabContainer).firstElementChild;
    

    instead of firstChild

    0 讨论(0)
  • 2020-11-29 08:03

    I would recommend anyone trying to work with the DOM in javascript to use a library like jquery. It will make your life much easier.

    You could then rewrite the JS function as fallows:

    function processTabs(TabContainer, PageContainer, Index) {
        var tabContainer = document.getElementById(TabContainer);
    
        // jquery used to find all the <li> elements
        var tabs = $(tabContainer).filter('li');
    
        // use the jquery get( index ) function to retrieve the first tab
        var tab = tabs.get(0);
        var i = 0;
        .... more code
    }
    
    0 讨论(0)
  • 2020-11-29 08:09

    You should skip the TextNodes, a simple function can help you:

    function getFirstChild(el){
      var firstChild = el.firstChild;
      while(firstChild != null && firstChild.nodeType == 3){ // skip TextNodes
        firstChild = firstChild.nextSibling;
      }
      return firstChild;
    }
    

    Usage:

    var tabContainer = document.getElementById(TabContainer);
    var tabs = getFirstChild(tabContainer);
    
    0 讨论(0)
  • 2020-11-29 08:13

    You can use node.firstElementChild to ignore leading text, or use a library like jQuery which takes care of this.

    0 讨论(0)
  • 2020-11-29 08:14

    With a an eye also on efficiency, this function returns firstChild element node of el

    function firstChildElement(el)
    {
        el = el.firstChild;
        while (el && el.nodeType !== 1)
           el = el.nextSibling;
        return el;
    }
    
    0 讨论(0)
  • 2020-11-29 08:20

    Use element.querySelector("*") to get the first child Element.

    Demo:

    var container = document.getElementById("container")
    
    console.log(container.querySelector("*")) // <div>This is a test</div>
    console.log(container.firstChild) // #text
    console.log(container.childNodes[0]) // #text
    <div id="container">
      <div>This is a test</div>
    </div>

    0 讨论(0)
提交回复
热议问题