Home > Software engineering >  I can't use classList in Js. Can anyone help me with this
I can't use classList in Js. Can anyone help me with this

Time:06-24

so this is the line of JS I have written.

function jumpPlayer() {
    let character = document.getElementById("player");

    character.classList.add("jumpPlayer");
}

fairly simple, there is a Id called 'player' and I want to add class called 'jumpPlayer' when a button is clicked but something is going wrong.

this is the error message

script.js:4 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at jumpPlayer (script.js:4:15)
    at HTMLDivElement.onclick (index.html:19:50)

by the way here is the html

<body>
    <div >
        <div ></div>
        <div  id="player"></div>
        <div ></div>
        <div ></div>
        <div ></div>

        <div  onclick="jumpPlayer()"></div>
    </div>



    <script src="./script.js"></script>
</body>

CodePudding user response:

In the html, did you declare a player id? Or a class?

If it's class change getElementById to getElementByClassName

CodePudding user response:

mira lo que pasa es que el document.getElementById() no esta encontrando el id que le pasaste, por lo devuleve null y en la siguiente linea tratas de ver la classList de null.

lo que puedes hacer es mirar tu html si existe el id , si esta bien escrito mayusculas, espacios, luego antes de mirar el classList has un console.log() de el elemento que seleccionaste asi podiras saber si, lo obteniendo....quedo atento

Cris.

  • Related