0

I am attempting to declare a new audio element in JavaScript. This is what I have written.

//Creating audio object
var audio = document.createElement("AUDIO");
audio.src = '/beats/vibe/lofi2.wav';
audio.controls = true;
audio.loop = false;
audio.autoplay = false;

I am receiving the following error: 'document' is not definded [no-undef]

Any clues as to why this wont work? Thanks!

3
  • 2
    where and when do you get this error ? looks like a linting error, not a browser error Commented Dec 26, 2017 at 7:25
  • That sounds like an eslint error. You'll need to tell it you're writing for web (if that's what you're doing) Commented Dec 26, 2017 at 7:26
  • It is an eslint error, and yes I am developing for web. Sorry wasn't aware that changed anything. Neither of the below solutions fixed it for me. Thanks! Commented Dec 26, 2017 at 17:58

2 Answers 2

0

Try using window.document. Replace

var audio = document.createElement("AUDIO");

with

var audio = window.document.createElement("AUDIO");

Or in some cases we can also include /*global document require*/ on top of the script files. This will ensure that document is available for the script.

Sign up to request clarification or add additional context in comments.

1 Comment

This just moved the error to window. How would I implement that second solution?
0

The object must be inserted into DOM. After crafting your audio tag, use:

document.body.appendChild(audio);

Demo

var audio = document.createElement("AUDIO");
audio.src = 'https://vocaroo.com/media_command.php?media=s1XsCD8OHZPI&command=download_mp3'
audio.controls = true;
audio.loop = false;
audio.autoplay = false;
document.body.appendChild(audio);

5 Comments

Is there a way to do this with an external JavaScript file?
@CalebSmith Yes, sir
@CalebSmith { "env": { "browser": true } } in your .eslintrc file. Refer to this post
Would I just add the .eslintrc file to the folder? Do I need to reference it in any way in my HTML or JavaScript file?
No problem, sir. To summarize, it was an eslint problem but keep in mind that your code will run in a browser (as long as you add the tag to DOM ex.document.body.appendChild(audio);)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.