Trying to understand undefined value in JS console log

Viewed 43

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 class="theme-switch-wrapper">
   <span id="music-player">some text</span>
     <i id="playBtn" class="fa-solid fa-circle-play"></i>
     <i id="pauseBtn" class="fa-regular fa-circle-pause"></i>
 </span>
 </div>
2 Answers

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 class="theme-switch-wrapper">
      <span id="music-player">some text
        <i id="playBtn" class="fa-solid fa-circle-play"></i>
        <i id="pauseBtn" class="fa-regular fa-circle-pause"></i>
      </span>
    </div>
    <script>
      const playToggle = document.getElementById('music-player');
        function changeIcon(){
        console.log(playToggle.children);
       }
      playToggle.addEventListener('click', changeIcon);
    </script>
  </body>
</html>

enter image description here

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

        playToggle.addEventListener('click', changeIcon);
    <div class="theme-switch-wrapper">
        <span id="music-player">some text
        <i id="playBtn" class="fa-solid fa-circle-play"></i>
        <i id="pauseBtn" class="fa-regular fa-circle-pause"></i>
        </span>
    </div>

Related