我有这样的html,这是一个包含一系列文件名的列表:
<ul>
<li class="attachment"><i></i> somefile.pdf</li>
<li class="attachment"><i></i> somefile.csv</li>
</ul>
我想将类添加到“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";
}
}
}
答案 0 :(得分:1)
childNodes[0]
或firstChild
是你可能正在寻找的东西
att[i].childNodes[0].className += " icon-file-excel";
或
att[i].firstChild.className += " icon-file-excel";