Search code examples
javascriptwordpressvideodivi-theme

Can I use javascript to add or remove attributes from a Video tag?


I don't know JavaScript and I want to add some attributes to a video tag. Is it possible to use JS code that can affect all the videos on one page?

Please see the below code I tried this after some online search not sure if it is correct or not!

I appreciate your help.

function playVideo() {
    var elementVar = document.getElementsByTagName("video");
    elementVar.setAttribute("autoplay: autoplay" || "loop: loop" || "controls: false") ;
}

Solution

  • You can definitely set attributes on an element with Javascript. However, the setAttribute function needs to be used differently. It takes two arguments:

    • The name of the attribute
    • The value for that attribute

    So in your case this would be a correct way to set the autoplay attribute:

    elementVar.setAttribute("autoplay","autoplay")
    

    Also, I'm not sure what does the or operator (||) is supposed to be doing between the strings. But it looks like you want to set all of those attributes. That needs to be done with 3 calls, like this:

    elementVar.setAttribute("autoplay","autoplay")
    elementVar.setAttribute("loop","loop")
    elementVar.setAttribute("controls","false")