0

I'm totally stumped as to why my btn variable comes out null.

I definitely have a value for melody.id, checked in the debugger.

I have successfully gotten the button with hard coding the "1" (the current melody.id) with the following code:

let btn = document.querySelector("button[data-id='1']")

Yet when I try to interpolate melody.id, I get null

let button = document.querySelector(`button[data-id="${melody.id}"]`)

I have backticks and other types of elements this way. Do buttons, not like interpolation?

function getMelodies() {
    fetch(endPoint)
      .then(res => res.json())
      .then(melodies => {
            console.log(melodies.data)
            melodies.data.forEach(melody => {
            const melodyMarkup = `
                <tr data-id=${melody.id}>
                    <td>${melody.attributes.title}</td>
                    <td>${melody.attributes.key}</td>
                    <td>${melody.attributes.user.name}</td>
                    <td><button data-id=${melody.id}>Play</button></td>                      
                </tr>`
                let btn = document.querySelector(`button[data-id="${melody.id}"]`)

                btn.addEventListener("click", (e) => retrieveMelody(e) )
                
                document.querySelector('#melody-container').innerHTML += melodyMarkup
            });
        });
}

Maybe I just need some fresh eyes.

Rohit416
  • 3,416
  • 3
  • 24
  • 41
mlgvla
  • 17
  • 3
  • 1
    You are querying when it only exists in `melodyMarkup ` string, before it is inserted in the DOM. Therefore the DOM query returns null. Do insertion first – charlietfl Dec 31 '20 at 02:31
  • Brilliant! That did the trick! And makes perfect sense, of course. I'm still new to this. Thanks again! – mlgvla Dec 31 '20 at 02:42

0 Answers0