1

I'm trying to find a way to get the source code of a video from a page and safe it into a variable in JavaScript. I already tried many ways, but every time I get "undefined" back.

<video width="800" height="450" style="width: 100%;" class="video" data-ended="/lernen/00/done" 
src="/media/video/99.webm">
<source type="video/mp4" src="/media/video/99.mp4">
</object>
</video>

I tried this, and thought that would look for the source within the class and store it in the variable. I just started using JavaScript today,

var src = document.getElementsByClassName("video").src
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Shervin
  • 29
  • 4
  • 2
    `getElementsByClassName` returns an array like object, which will not have a `src` property. You would need to get the `[0].src` perhaps – Taplar Apr 21 '20 at 18:05
  • thank u a lot! Another question: do src return a string? – Shervin Apr 21 '20 at 18:17

2 Answers2

3

If you use class and getElementsByClassName() method it returns list of result so, you need to take the first one.

If you use id and getElementById() method then it returns just one element then you take take it directly.

If you use querySelector() method it returns first element then you can take it directly.

If you use querySelectorAll() method it returns list of elements matched, then you can take first element of list.

clas with first element or queryselector(it returns always first one)

src = document.getElementsByClassName("video")[0].src;
console.log(src);
 src = document.getElementById("video").src;
console.log(src);
src = document.querySelector(".video").src;
console.log(src)
src = document.querySelectorAll(".video")[0].src;
console.log(src)
<video width="800" height="450"id="video" style="width: 100%;" class="video" data-ended="/lernen/00/done" 
src="/media/video/99.webm">
<source type="video/mp4" src="/media/video/99.mp4">
</object>
</video>
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
2

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

So you have to use one of the elements from the array, first [0] for example:

var src = document.getElementsByClassName("video")[0].src
console.log(src)
<video width="800" height="450" style="width: 100%;" class="video" data-ended="/lernen/00/done" src="/media/video/99.webm">
<source type="video/mp4" src="/media/video/99.mp4">
</object>
</video>
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39