user1157123
user1157123

Reputation:

Changing properties of multiple <video> tags from Javascript

I can change the source of an HTML5 video at runtime like this:

<video autoplay></video>
<script>
    var video = document.querySelector('video');
    video.src = "http://new/url";
</script>

But if I have multiple video's on the page how do I refer to each of them in the script and access their individual attributes?

Am I able to provide a name string for the video entities? I am expecting to be able to do something like this:

<video name="video0" autoplay></video>
<viedo name="video1" autoplay></video>
<script>
    video0.src = "http://first/url";
    video1.src = "http://second/url";
</script>

Upvotes: 0

Views: 338

Answers (4)

Dennis Traub
Dennis Traub

Reputation: 51634

You can provide an id. To easily access the nodes I'd recommend using jQuery:

<video id="video0" autoplay></video>
<video id="video1" autoplay></video>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        var video0 = $('#video0');
        var video1 = $('#video1');
        video0.attr('src', 'http://first/url');
        video1.attr('src', 'http://second/url');
    });
</script>

Upvotes: 0

MrCode
MrCode

Reputation: 64526

Either assign the elements a unique ID attribute and use document.getElementById(), or use document.getElementsByTagName('video') to retrieve all videos on the page.

Upvotes: 0

user1726343
user1726343

Reputation:

This gets an HTMLCollection of all video tags

var videos = document.querySelectorAll('video');

You can select them by name using:

var videos = document.querySelector('video[name="video0"]');

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

I suggest to retrieve them by tag name with pure JS:

var videos = document.getElementsByTagName('video');
for (var i = 0; i < videos.length; i++) {
    videos[i] // the i-th video
}

If you're open to jQuery you can do the same with jQuery:

var videos = $('video');
videos.each(function (index, videoElement) {
    // this refers to the current video.
});

Upvotes: 0

Related Questions