简体   繁体   English

如何使用javascript将类添加到子元素?

[英]How do I add a class to a child element with javascript?

I have html like this, which is a list with a series of file names: 我有这样的html,这是带有一系列文件名的列表:

<ul>
    <li class="attachment"><i></i> somefile.pdf</li>
    <li class="attachment"><i></i> somefile.csv</li>
</ul>

I'd like to add the class to the "i" element rather than the attachment div, but I can't figure out how do it. 我想将类添加到“ i”元素而不是附件div中,但是我不知道该怎么做。

function addIcon() {
    var att = document.getElementsByClassName('attachment');

    for (var i = 0; i < att.length; i++)
    {
       if (att[i].innerHTML.indexOf(".csv") != -1) {

           att[i].className += " icon-file-excel";
       }
       else if (att[i].innerHTML.indexOf(".xls") != -1) {

           att[i].className += " icon-file-excel";
       }
       else if (att[i].innerHTML.indexOf(".pdf") != -1) {

           att[i].className += " icon-file-pdf";
       }
       else if (att[i].innerHTML.indexOf(".doc") != -1) {

           att[i].className += " icon-file-word";
       }
       else if (att[i].innerHTML.indexOf(".jpg") != -1) {

           att[i].className += " icon-file-image";
       }
       else if (att[i].innerHTML.indexOf(".tif") != -1) {

           att[i].className += " icon-file-image";
       }
       else if (att[i].innerHTML.indexOf(".png") != -1) {

           att[i].className += " icon-file-image";
       }
       else if (att[i].innerHTML.indexOf(".doc") != -1) {

           att[i].className += " icon-file-word";
       }
       else{
           att[i].className += " icon-file-text";
       }
    }
}

childNodes[0] or firstChild are the things you're probably looking for childNodes[0]firstChild是您可能正在寻找的东西

att[i].childNodes[0].className += " icon-file-excel";

or 要么

att[i].firstChild.className += " icon-file-excel";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM