Search code examples
javascripthtmlvideosrc

Target video source in HTML with JavaScript


My video is not playing after editing the source via JavaScript, can you help me with that?

HTML : <video class="background-video" controls muted loop autoplay>
       <source id="vid_tag" type="video/mp4"></video>

JS : document.querySelector('#vid_tag').src = "_1/video/bvid_1.mp4"

Solution

  • It could be an error with the path, maybe you wrote it wrong and the browser does not find it.

    Possible Solution:

    (1) Fix HTML:
    The ID should be written in the <video> tag's setup (not put in <source> tag)

    <video id="vid_tag" class="background-video" controls muted loop autoplay>
    <source src="nothing.mp4" type="video/mp4">
    </video>
    

    (2) Fix JS:

    Replace document.querySelector('#vid_tag') with something more direct like document.getElementById("vid_tag") where you access by the specific ID of the Element you want.

    document.getElementById("vid_tag").src = "_1/video/bvid_1.mp4"; //# set new src
    document.getElementById("vid_tag").load(); //# decode (process) the new file