简体   繁体   中英

Console says element is “null”

I've started to create some kind of image slider but right at the beggining i've reached a problem

Console says that my img1 and others are "null"..

Where's my mistake ?

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

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

Your selector is incorrect. .images_first active would select an element with tag name active that is a descendant of an element with class images_first . Ie it would find the inner element in this example:

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

However, what you actually seem to want is to find the element that has both classes, images_first and active . This is written as

.images_first.active

Learn more about CSS selectors on MDN .


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM