控制台说元素是“null”

时间:2017-09-25 21:11:10

标签: javascript dom css-selectors

我已经开始创建某种图像滑块但是在开始时我遇到了问题

控制台说我的img1和其他人都是“空”..

我的错误在哪里?

let img1 = document.querySelector('.images_first active');
let img2 = document.querySelector(".images_second");
let img3 = document.querySelector(".images_third");

const fw = document.querySelector(".test-button_forward");
const back = document.querySelector(".test-button_backwards");

let clicks = 0;
console.log(img1);


fw.addEventListener('click', function()
 {
  img1.classList.remove('active');
  img2.classlist.add("active");

  clicks++;

});

Full version is here

2 个答案:

答案 0 :(得分:1)

let img1 = document.querySelector('.images_first.active');

答案 1 :(得分:1)

您的选择器不正确。 .images_first active会选择标记名称 active的元素,该元素是具有类images_first的元素的后代。即它会在这个例子中找到内部元素:

<div class="images_first">
  <active></active>
</div>

但是,您实际上想要的是找到包含两个类images_firstactive的元素。这写成

.images_first.active

Learn more about CSS selectors on MDN

相关:Why does jQuery or a DOM method such as getElementById not find the element?