Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将类添加到没有jQuery的第一个子ul_Javascript - Fatal编程技术网

Javascript 将类添加到没有jQuery的第一个子ul

Javascript 将类添加到没有jQuery的第一个子ul,javascript,Javascript,这行代码使用纯javascript编写: $('.container ul:first-child').addClass('new'); 将id属性添加到ul,然后: var list = document.getElementById("myList").firstChild; list.classList.add("mystyle"); 您可以尝试以下方法: document.querySelectorAll(".container ul:nth-child(1)"); 现在添加类:

这行代码使用纯javascript编写:

$('.container ul:first-child').addClass('new');

将id属性添加到ul,然后:

var list = document.getElementById("myList").firstChild;
list.classList.add("mystyle");
您可以尝试以下方法:

document.querySelectorAll(".container ul:nth-child(1)");
现在添加类:

document.querySelectorAll(".container ul:nth-child(1)").forEach(function(c){
   c.classList.add("my-class");
});
如果我使用document.querySelector all,是因为该文档可能包含多个.container类,否则您可以使用其他版本的querySelector:

如果要使用simple for而不是forEach:


document.querySelector.container ul:first child.classList.add'new'为您的ul添加一个id属性是否有理由在:first child?上使用第n-child1?第n-child1更灵活。两者都可以使用:还值得指出的是,如果需要IE支持,则需要使用polyfill。您可以使用simple。请看我的最后一部分代码。很好,我刚刚从OP中预测了下一个问题,它说forEach不是一个函数:D
document.querySelector(".container ul:nth-child(1)").classList.add("my-class");
var All = document.querySelectorAll(".container ul:nth-child(1)");
for(var c in All) if(All.hasOwnProperty(c)) All[c].classList.add("my-class");}