简体   繁体   中英

Uncaught TypeError: playlist.querySelector is not a function

I'm trying to change the main video on the page to another video when a user clicks on one of the thumbnail img links.

Essentially this code is supposed to:

  • grab each video playlist (if there are 1 or more)
  • grab each playlists video tag and source tag
  • loop through all the video links
  • add a click listener to each link which grabs the added data-video-src attribute that I added, and apply it to the video source,
  • load the video.

Here is the HTML: This is the HTML code

Below is the JavaScript but when I run it I get:

"Uncaught TypeError: playlist.querySelector is not a function"

What am I doing wrong?:

ChangeVideo.js

the problem is because for playlist in ... with have playlist as the index of the array.

try this

var playlists = document.querySelectorAll('.video-playlist');
for (var i = 0; i < playlists.length; i++) {
  var playlist = playlists[i];
  ...
});

and also the internal for in loop needs to change too.

thanks

You are doing for(playlist in document.querySelectorAll('.video-playlist')) which will set the value of playlist with the value of key of document.querySelectorAll('.video-playlist') . And since document.querySelectorAll('.video-playlist') is a array type the key will be 0 , 1 , 2 , and so on. So, playlist will have numeric value 0 , 1 , 2 , ... With this playlist.querySelector will give you that error

"Uncaught TypeError: playlist.querySelector is not a function"

To overcome this you need to select each element of document.querySelectorAll('.video-playlist') rather than its index . For that you need to change the for loop to use of instead of in like

for(playlist of document.querySelectorAll('.video-playlist'))

When you use of in the for loop then it will assign each element of document.querySelectorAll('.video-playlist') to playlist . And when you get the element in playlist , the function querySelector will be valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM