Reputation: 53
Based on written code below, the expected result should be returning the DOM element '' in the console, when clicking the 'a' which has keyCode 65. When I run the code and inspect it returns null in the console.
Part of the source code:
<audio data-key="65" src="#"></audio>
<script>
window.addEventListener('keydown',function(e){
const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
console.log(audio);
});
</script>
Upvotes: 2
Views: 265
Reputation: 22595
If you want to use es6 placeholder you need to use backtick
(`) instead of single apostropthe.
`audio[data-key="${e.keyCode}"]`
Other option is just to use string concatenation.
'audio[data-key="'+e.keyCode+'"]'
Upvotes: 3
Reputation: 8787
You need to concatenate the keycode into the selector string, not include it as a template string.
Change it to this:
const audio = document.querySelector('audio[data-key="'+e.keyCode+'"]');
Upvotes: 1