As part of my project, I am attempting to construct a basic piano utilizing Vanilla Js that encompasses all the sound notes such as Do, Re, Mi. Unfortunately, I have encountered an error linked to the querySelector function for data-* attributes. Below is the relevant segment of my code:
let keyArr = document.querySelectorAll(".musicKey");
var audioKeyProp;
keyArr.forEach(function(item) {
let tempVal = item.getAttribute('data-key');
audioKeyProp[tempVal] = document.querySelector(`audio[data-key=${tempVal}]`);
//For debugging
console.log(audioKeyProp[tempVal]);
});
<body>
<div id="main-div">
<div class="keys">
<div data-key="100" class="musicKey">
<p>D</p><span>(Do)</span></div>
<div data-key="114" class="musicKey">
<p>R</p><span>(Re)</span></div>
<!--there are more such div elements. For simplicity's sake, only two are mentioned -->
</div>
</div>
<audio data-key="100" src="audio/do.mp3" type="audio/mpeg"></audio>
<audio data-key="114" src="audio/re.mp3" type="audio/mpeg"></audio>
<!--there are additional audio elements. To keep it brief, only two were included -->
</body>
The objective is to produce sound with each keystroke. Initially, I intend to pair each audio element with its corresponding key.
I am encountering errors like,
"soundBox.js:7 Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'audio[data-key=100]' is not a valid selector."
Could you please pinpoint what I might be overlooking? Is it prohibited to use the data-key attribute for two different elements (div and audio in this instance)? My browser of choice is Chrome.