Search code examples
javascripthtmlspeech-synthesis

how to resolve "cannot read property appendChild of null" in the following code?


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> speech synthesizer</title>
  </head>
  <body>
    <div class="voiceinator">
      <h1> My Speech Synthesizer </h1>

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    <label for="rate">Rate:</label>
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    <label for="pitch">Pitch:</label>
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>
    </div>
 <script type="text/javascript">

  const msg = new SpeechSynthesisUtterance();
  let voices = [];
  var voicesDropdown = document.querySelector('[name="voices"]');
  const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
  const speakButton = document.querySelector('#speak');
  const stopButton = document.querySelector('#stop');
  msg.text = document.querySelector('[name="text"]').value;

  function populateVoices()
  {
    voices = this.getVoices();

    for( var i=0 ; i<voices.length ; i++ ){
      var opt = voices[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      voicesDropdown.appendChild(el);
    }

  }
  //when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
  speechSynthesis.addEventListener('voiceschanged', populateVoices);
 </script>
  </body>
</html>

THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

SPEECH SYNTHESIZER.html:45 Uncaught TypeError: Cannot read property 'appendChild' of null at SpeechSynthesis.populateVoices (SPEECH SYNTHESIZER.html:45)

Also please tell me how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang


Solution

  • The name on the <select> is voice not voices. But simpler and more efficient to get that element by ID

    Change:

    var voicesDropdown = document.querySelector('[name="voices"]');
    

    To

    var voicesDropdown = document.querySelector('#voices');