Home > OS >  Trying to understand undefined value in JS console log
Trying to understand undefined value in JS console log

Time:09-11

I've just taken my first steps into learning Javascript.

I'd like to us console log to find the children of my playToggle button but I'm getting Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'). Please help me learn what I am doing wrong, I was under the impression that I had given playToggle a value.

const playToggle = document.getElementById('music- 
player');
 function changeIcon(){
     console.log(playToggle.children);
 }
 
 playToggle.addEventListener('click', changeIcon);

HTML:

 <div >
   <span id="music-player">some text</span>
     <i id="playBtn" ></i>
     <i id="pauseBtn" ></i>
 </span>
 </div>

CodePudding user response:

if you have the script tag placed correctly and no typo with id it should just work fine.

<!DOCTYPE html>
<html>
  <head>
    <title>Show Children</title>
  </head>
  <body>
    <div style="border: 2px solid #443212; cursor: pointer;" id="playBtn">
      <h1>Test Playground</h1>
      <p>This is a playground</p>
    </div>
    <script>
      const playToggle = document.getElementById('playBtn');

        function changeIcon() {
          console.log(playToggle.children);
        }

        playToggle.addEventListener('click', changeIcon)

    </script>
  </body>
</html>

enter image description here

CodePudding user response:

    const playToggle = document.getElementById('music-player');
        
        function changeIcon() {
            console.log(playToggle.children);
        }

        playToggle.addEventListener('click', changeIcon);
    <div >
        <span id="music-player">some text
        <i id="playBtn" ></i>
        <i id="pauseBtn" ></i>
        </span>
    </div>

  • Related