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 ></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 https://www.youtube.com/watch?v=jZL9gVwxO-U" rel="nofollow noreferrer">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
CodePudding user response:
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.js
file 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 ></div> <script src="app.js"></script>