Add class to first child using javascript

前端 未结 3 1196
臣服心动
臣服心动 2021-01-12 18:04

is there any reason this chain does not work? It does not add the class:

document.getElementsByTagName(\'nav\')[0].firstChild.className = \"current\"
         


        
相关标签:
3条回答
  • 2021-01-12 18:19

    That's because you have text nodes between nav and a. You can filter them by nodeType:

    var childNodes = document.getElementsByTagName('nav')[0].childNodes;
    for (var i = 0; i < childNodes.length; i++) {
        if (childNodes[i].nodeType !== 3) { // nodeType 3 is a text node
          childNodes[i].className = "current";  // <a>
          break;
        }        
    }
    

    It may seem strange but, for example, if you have the following markup:

    <nav>
    <a>afsa</a>
    </nav>
    

    Here's a DEMO.

    Why does this happen? Because some browsers may interpret the space between <nav> and <a> as an extra text node. Thus, firstChild will no longer work since it'll return the text node instead.

    If you had the following markup, it'd work:

    <nav><a>afsa</a></nav>
    
    0 讨论(0)
  • 2021-01-12 18:20

    Jquery can make this very easy:

    $("#nav:first-child").addClass("current");
    
    0 讨论(0)
  • 2021-01-12 18:42

    The statement:

    document.getElementsByTagName('nav')[0].firstChild.className = "current"
    

    is somewhat fragile as any change in the assumed document structure breaks your code. So more robust do do something like:

    var links, 
        navs = document.getElementsByTagName('nav');
    
    if (navs) links = nav[0].getElementsByTagName('a');
    
    if (links) links[0].className = links[0].className + ' ' + 'current';
    

    You should also have robust addClassName and removeClassName functions.

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