Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'length' of null at rating.js:4

Tags:

javascript

This is my own rating plugin

But I'm getting an error when I run this

This is the error:

Uncaught TypeError: Cannot read property 'length' of null
at rating.js:4

This is my rating.js

const stars = document.querySelector(".rating".children);
const ratingValue = document.querySelector("#rating-value");

for (let i = 0; i < stars.length; i++) {
    stars[i].addEventListner("mouseover", function () {
        for (let j = 0; j < stars.length; j++) {
            stars[j].classList.remove("fa-star");
            stars[j].classList.add("fa-star-o");
        }
        for (let j = 0; j <= i; j++) {
            stars[j].classList.remove("fa-star-o");
            stars[j].classList.add("fa-star");
        }
    })
    stars[i].addEventListner("click", function () {
        ratingValue.value = i + 1;
    })
}

I'm not an expert in JavaScript but I need to use this in my project.

like image 304
Jazim Max Avatar asked Jan 25 '23 21:01

Jazim Max


2 Answers

Your selector is wrong, as you are trying to pass the children property of a string (which does not exist) to document.querySelector. This is equivalent to document.querySelector(undefined), which returns null.

Change

const stars = document.querySelector(".rating".children);

To

const stars = document.querySelector(".rating").children;

Moreover, addEventListner should be addEventListener.

like image 65
Unmitigated Avatar answered Jan 27 '23 09:01

Unmitigated


This is what going wrong.

const stars = document.querySelector(".rating".children);
// should be
const stars = document.querySelector(".rating").children;

like image 27
8HoLoN Avatar answered Jan 27 '23 11:01

8HoLoN