Issue with querySelector() method when using HTML5 data-* attribute

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.

Answer №1

Ensure attribute values are enclosed in quotes, refer to Attribute selectors

document.querySelector(`audio[data-key="${tempVal}"]`)

let keyArr = document.querySelectorAll(".musicKey");
var audioKeyProp;
keyArr.forEach(function(item) {

  //console.log(item);
  let tempVal = item.getAttribute('data-key');
  console.log(document.querySelector(`audio[data-key="${tempVal}"]`));
});
<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. To make it simple I only mentioned two -->
  </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>

Answer №2

To add this value to an array, follow these steps:

let keys = document.querySelectorAll(".musicKey");
let audioKeys = [];
keys.forEach(function (element) {

    console.log(element);
    let tempValue = element.getAttribute('data-key');
    audioKeys.push(document.querySelector(`audio[data-key='${tempValue}']`));
    console.log(audioKeys);
});

Answer №3

let list = document.querySelectorAll(".musicKey");
var audioKeyProp = {};
Array.prototype.forEach.call(list, function (item,i) {
    let tempVal = item.getAttribute('data-key');
    let dom     = document.querySelector('audio[data-key="'+tempVal+'"]');
    if(dom)
        audioKeyProp[i] = dom.src 
});
console.log(audioKeyProp)
<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 divs like this. For simplicity's sake, I only included two-->
    </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>
 </body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Document.querySelector() in combination with Bootstrap CSS may lead to unexpected results

CSS & HTML <html lang="en"> <head> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384x ...

Styling Circles with CSS

HTML: <ul class="list_header"> <li><a href="#">06 december 2013</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> ...

What is the process for retrieving a client cookie, specifically one containing a session ID, that has been generated by node

I thought I had a grasp on how Cookies functioned, but it seems like I was mistaken as I'm encountering some issues: Despite trying to display a cookie using document.cookie and testing with alert(document.cookie); in my code, I am unable to do so. ...

Creating an event based on the date field in a database document (Node.js + MongoDB): A complete guide

I've developed a web server using NestJS where users can create auctions. Each auction document includes an end_date field, and I'm looking to automate an event when this date is reached. Is there a method to schedule or activate a function in M ...

JavaScript escape sequences are used to represent characters that are

Is there a way to pass a variable to another function in this scenario? I am inserting a textarea using JavaScript with single quotes, but when the function myFunction(abc123) is called, it appears like this, whereas it should look like myFunction('ab ...

Is going too deep a bad practice in Vue.js?

Unleashing the full potential of Vue.js component styling involves leveraging the power of ::v-deep to target CSS classes within nested components, as shown below: <template> <div class="parent"> <Child /> <!-- contains ...

The Dependability of LocalStorage in Phonegap

I am currently developing a PhoneGap application that requires storing user data. The app will prompt the user to input a URL during the initial startup. Since URLs can be lengthy, I want to save it on the user's device to avoid the need for them to r ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

What is the process for modifying the django password reset confirmation page?

As a fresh Django developer, my goal is to customize the django password_reset_confirm.html page with a new HTML file called change_pwd.html. <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta http-equiv="Conte ...

What is the process for converting an array of objects into an array of form groups?

I am looking to utilize the array function of the formbuilder to handle formcontrol arrays. I have a custom object array that I need to integrate into a FormArray, but it seems to only accept FormGroup as arguments. How can I convert my array of custom obj ...

Alternative names for Firefox's "error console" in different browsers

Are there similar tools to Firefox's "Error console" available in other web browsers? I rely on the error console for identifying JavaScript errors, but I haven't found a straightforward way to view error messages in other browsers like Internet ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

Ways to eliminate an item from an array when the value of the object is not present

I am facing an issue with removing objects from an array that do not contain the data object. I have attempted to use the filter method but have not been successful. results.filter(obj => obj.data === undefined) results = [ {id: 1, location: 'a&a ...

Unable to locate the source of ERR_HTTP_HEADERS_SENT error

I've come across this persistent HTTP Headers error that's been giving me a headache for the past three days. I'm not trying to sound dramatic, but it's been a real struggle. The error log points towards an issue with async/await, but p ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

The issue of infinite scroll functionality not functioning properly when using both Will Paginate and Masonry

I'm having trouble getting the Infinite Scroll feature to work on my website. I've successfully implemented Masonry and Will Paginate, but for some reason, the Infinite Scroll isn't functioning as expected. I suspect that the issue lies wit ...

Upgrade from jquery1 to jquery 2: enhancing selector functionality

Having issues with selectors and brackets : var myInputId = $(input).attr("id") "value-5379-32433[]" This ID belongs to a checkbox list. Trying to select all elements with this ID : $("#" + myInputId); Uncaught Error: Syntax error, unrecognized expressi ...

Using URL parameters in Node.js applications

I am encountering an issue with my nodejs setup, and I am hoping someone can assist me. My challenge lies in trying to pass a parameter with a specific value to a page.html file, like this: page.html?s=1 However, I am encountering a problem where the pa ...

"Error message: The geocoder from Google Maps cannot locate the address

Trying to utilize the geocoder for obtaining coordinates of the address below: 1945 Barton Street, Hamilton, ON, L8H2Y7 A search on Google Maps itself yields the address: . The geocode URL also returns results without any issues. http://maps.googleapis.c ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...