0

I've seen answers dealing with selecting elements in CSS and I'm wondering if it is possible to perform the following with one line using a wildcard in jQuery?

jQuery('.youtube-video-1')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('.youtube-video-2')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('.youtube-video-3')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');

I've tried:

jQuery('.youtube-video-\\S*')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
jQuery('[class^=youtube-video-]')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
Line One
  • 13
  • 4
  • 1
    [this covers how to strcture your selector](https://stackoverflow.com/questions/49189549/css-selector-wildcard-inside-class-name), however your handling of working with a collection rather than one element is also incorrect. [0] will always reduce the collection to 1 element, not all of them. – Kevin B Mar 24 '23 at 14:41
  • 2
    Why not just add a `youtube-video` class to all of elements instead? – Heretic Monkey Mar 24 '23 at 14:41
  • @KevinB [0] is used here to get to the DOM element of the SINGLE iframe with `class="youtube-video-1"` so Heretic Monkey's suggestion is better and even better to not use jQuery here at all. `document.querySelectorAll('youtube-video-class').forEach(vidFrame => vidFrame.contentWindow.postMessage(.....))` – mplungjan Mar 24 '23 at 14:44
  • 1
    @mplungjan of course, though, using a single classname doesn't affect the [0] problem. In both cases that has to be resolved as well. – Kevin B Mar 24 '23 at 14:45
  • I'll try your suggestion @Heretic Monkey – Line One Mar 24 '23 at 14:46
  • Thanks @mplungjan. I got there with: `document.querySelectorAll('.youtube-video').forEach(vidFrame => vidFrame.contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*'));` – Line One Mar 24 '23 at 15:01
  • jquery version would be : `$(".youtube-video").each((_, vidFrame) => vidFrame.contentWindow... );` – freedomn-m Mar 24 '23 at 15:06

0 Answers0