Add class to first child using javascript

前端 未结 3 1197
臣服心动
臣服心动 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: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.

提交回复
热议问题