SaMo
SaMo

Reputation: 45

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") ;
}

Upvotes: 0

Views: 1715

Answers (2)

BenVida
BenVida

Reputation: 2312

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")

Upvotes: 1

jeffkmeng
jeffkmeng

Reputation: 879

You can definitely use javascript to add attributes to a video tag, but you aren't using the proper syntax.

The proper syntax for setAttribute is:

.setAttribute(attrName, attrValue);

Note that it can also only set one attribute at a time, so you can't do "autoplay: autoplay" || "loop: loop".

Here's the code you probably want:

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

Upvotes: 1

Related Questions