Dav*_*Lee 1 javascript ecmascript-6
这是我的 html,它是从循环通过 PersonalityQuestions 表的 Rails 表单生成的。
<div id="carouselExampleControls" class="carousel slide" data-interval="false"
data-ride="carousel" data-pause="hover">
<div class="carousel-inner">
<div class="carousel-item text-center">
<h2>I want to be seen as successful</h2>
</div>
<div class="carousel-item text-center">
<h2>I don’t want to be seen as taking up too much space </h2>
</div>
<div class="carousel-item text-center">
<h2>I want to be seen as authentic and special</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
我想使用 javascript(遗憾的是没有 jQuery)将 的类添加active
到我的第一个孩子<div classs="carousel-inner">
结果应该是<div class="carousel-item text-center active">
我已经阅读了所有 Stackoverflow 帖子,但找不到答案。
这是我想出的最佳答案
document.getElementsByClassName('carouselinner').firstChild.classList.add('active');
但我收到一个错误:
Uncaught TypeError: Cannot read property 'classList' of undefined at <anonymous>:1:61
谁能告诉我我做错了什么?
您的尝试基本上有两个问题:
首先,getElementsByClassName()
返回具有所有给定类名的所有子元素的类数组对象。因此,您要从哪个索引中查找firstChild是不明确的。您已提供特定索引。
其次,对于问题(返回#text
或#comment
节点)node.firstChild
为避免
node.firstChild
返回#text
或#comment
节点的问题,ParentNode.firstElementChild
可用于仅返回第一个元素节点。但是,node.firstElementChild
对于 Internet Explorer 9 及更早版本,需要一个垫片。
所以你的代码应该是:
document.getElementsByClassName('carousel-inner')[0].firstElementChild.classList.add('active');
Run Code Online (Sandbox Code Playgroud)
但首选方法是:first-child
在querySelector()
with 中使用选择器classList.add()
:
document.getElementsByClassName('carousel-inner')[0].firstElementChild.classList.add('active');
Run Code Online (Sandbox Code Playgroud)
document.querySelector('.carousel-inner :first-child').classList.add('active');
Run Code Online (Sandbox Code Playgroud)
.active {color: red}
Run Code Online (Sandbox Code Playgroud)