I am following along with a tutorial to create an audio player. The index.html file has a class named audioPlayer as shown below:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div class="audioPlayer"></div>
<script src="AudioPlayer.js"></script>
</body>
</html>
The audioPlayer class is used as a querySelector in the JavaScript code below in order to attach additional elements:
class AudioPlayer {
constructor(selector = '.audioPlayer', audio = []) {
this.playerElement = document.querySelector(selector);
this.audio = audio;
this.currentAudio = null;
this.createPlayerElements();
}
createPlayerElements() {
this.audioElement = document.createElement('audio');
const playListElement = document.createElement('div');
playListElement.classList.add('playlist');
this.playerElement.appendChild(this.audioElement);
this.playerElement.appendChild(playListElement);
}
}
let player = new AudioPlayer()
At this point the tutorial creator is able to access index.html on a local web server and verify that the audio and div class="playlist></div elements have been appended to the original selector. When I run a local server (http-server installed globally via npm) and inspect the page, this has not occurred. The audioPlayer element is unchanged. The console shows no error messages, and I am able to inspect the script file in the browser so I know the path is correct.
The tutorial I am following can be viewed on YouTube. While the tutorial is 30 minutes long, the problem I have encountered should be reproducible by following only the first 5 minutes. The tutorial source code contains a dist directory and package.json showing parcel as a dependency.
Is it possible to create elements as attempted using only vanilla JavaScript, and if so, what am I missing?
There are many similar posts on SO. In order to avoid having this question marked as a duplicate, I will list the posts that I have carefully read and have not found pertinent to my situation:
- Using Node.js as a simple web server
- Creating HTML element via javascript not working
- div – createElement is not working?
- Why doesn't a simple createElement command work with JS and create an element in HTML DOM
- Why does this document.createElement("div) code not create an element?
- Javascript: function associated with create element not working
- Javascript createElement() not working in Chrome
>Solution :
It seems you didn’t (first) have the code that actually creates an instance of your AudioPlayer class, so neither constructor() nor createPlayerElements() gets executed.
In the video you referenced, check again what is discussed at around 4:10-4:30.
-
In an
app.jsfile enter:import AudioPlayer from './AudioPlayer'; const audioPlayer = new AudioPlayer(); -
Below the audio element in the body of your HTML, don’t include
AudioPlayer.js, but thisapp.js. So:<div class="audioPlayer"></div> <script src="app.js"></script>