0

I have a video and some JavaScript code. The code says

var videoIDRAW = getUrlVars()["watch"];
var videoID = videoIDRAW.toString();
var videoIDFILE = videoID.concat(".mp4");
var videofile = document.getElementById("vid");

videofile.setAttribute("src", videofile)

videofile is

<video width="912" height="513" controls >
<source id="vid" src="" type="video/mp4">

</video>

why do i get the TypeError: videofile is null?

EDIT: modified videofile.setAttribute("src", videofile.toString()), same error

Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
  • Your code seems to be semantic incorrect. You are trying to add the source id="vid" as src for itself. You have to generate a link for some kind and then add it to the source element. – Aaron Jan 11 '20 at 20:49
  • Aaron what do you mean by that –  Jan 11 '20 at 20:53
  • You get the DOM element and use the function toString on it which makes no sense at all. I post a working version. – Aaron Jan 11 '20 at 20:54
  • Seblor tried that, nothing new apparently –  Jan 11 '20 at 21:11
  • @lambdaguy101 Just make sure you are loading your script *after* the body has loaded, otherwise calling `document.getElementById` will return null (because the elements are not yet created) – Seblor Jan 11 '20 at 21:15

1 Answers1

1

toString() is not a magical tool. It should have been called by default anyway I think.

As Aaros pointed out, the issue lies in what your algorithm tries to do. You are trying to set a DOM element as the value of one of its own attributes. The src attribute of a video needs to be the video's URL (or blob, but that's more complicated).

Didn't you mean this ?

videofile.setAttribute("src", videoIDFILE); // Or videofile.src = videoIDFILE

Edit: Don't forget to execute your script after the body. Either by moving the script tag to the bottom of the body (but still inside), or you can use a listener like you can find there : How to execute a function when page has fully loaded?

Seblor
  • 6,947
  • 1
  • 25
  • 46
  • I can't edit my post but here's the code that I modified –  Jan 11 '20 at 21:17
  • var videoIDRAW = getUrlVars()["watch"]; var videoID = videoIDRAW.toString(); var videoIDFILE = videoID.concat(".mp4"); var videofile = document.getElementById("vid"); videofile.setAttribute("src", videoIDFILE) –  Jan 11 '20 at 21:17
  • it does the exact same thing –  Jan 11 '20 at 21:17
  • Have you looked at my new comment or edit ? Also you should be able to edit your question. – Seblor Jan 11 '20 at 21:18