通过javascript ES6将css类添加到第一个孩子

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

谁能告诉我我做错了什么?

Mam*_*mun 6

您的尝试基本上有两个问题:

首先,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-childquerySelector()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)