jon cena
jon cena

Reputation: 11

getting ID of HTML <source>

I am trying to load in the source of videos and sound files on my website from JSON files. I do this for other elements on my page using:

`$('#cimg').attr('src', jsonObj.cloud[0].refimage)`

This seems to work for things like images, but not for HTML 5 video and sound files where there is source tags like so:

<source id="cvid" src="" type="video/mp4">

I think that you can't create ID's in source tags, because the same method works for img tags.

Does anyone know how I can give or access the id from a source tag?

Upvotes: 1

Views: 1371

Answers (2)

Kaiido
Kaiido

Reputation: 136796

You can access the <source> element like any other element, be it by id.

What you did forget however, is that when you modify its src attribute, you have to call the .load() method of its container <video> element.

var vid = document.getElementById('vid');
var source = document.getElementById('cvid');
var src = ['http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_50mb.mp4', 'http://vjs.zencdn.net/v/oceans.mp4'];
var s = 0;

document.getElementById('btn').onclick = function(){
  
  // change the <source> 's src
  cvid.src = src[++s%src.length];
  // ask the <video> to load this new source
  vid.load();

  // could also be 
  // cvid.parentNode.load();
  
  }
<button id="btn">switch video source</button><br>
<video controls muted autoplay id="vid">
<source id="cvid" src="http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_50mb.mp4" type="video/mp4">
</video>

Upvotes: 0

omarjmh
omarjmh

Reputation: 13896

You could just grab the tag:

console.log($('source').attr('id'))

JSFiddle with your code

Upvotes: 2

Related Questions