HTML Element Selectors into Javascript WebSpeech API

  dom, html, javascript

Hoping someone can assist me with my code. I am trying to use the speakText variable to grab the paragraph in my HTML ("I am thirsty") and use the WebSpeech API to read the paragraph out loud. Unfortunately I can’t seem to get my selectors right…any ideas?

Here is my javascript:

const synth = window.speechSynthesis;
// Item to Play:
  var playElement = document.querySelectorAll(".speech_item");

  playElement.forEach(function (currentValue) {
    currentValue.addEventListener("click", onClickPlay(currentValue));

   function onClickPlay(currentValue) {
    speakText = new SpeechSynthesisUtterance(
      currentValue.querySelector("p").textContent
    );
    synth.speak(speakText);
  });

and my HTML:

       <div class="speech_item m-2" style="width: 6rem">
          <img
            class="card-img-top"
            src="{% static '/speech_items/water.png' %}"
            alt="Water Bottle"
          />
          <div class="card-body">
            <p class="card-text">I am thirsty</p>
          </div>
        </div>

a side note this code works, but only works for the first element:


    SpeechSynthesisUtterance(
    document.querySelector(".speech_item p").textContent
    );

Source: Ask Javascript Questions

LEAVE A COMMENT