9

In the example given here https://developers.google.com/youtube/iframe_api_reference you can see that instead of using standard css selector syntax there's a custom string syntax that seems to only refer to id.

<div id="player"></div>

// note no 'var' and yet this will work in strict mode
// since 'player' is being implicitly grabbed from the dom
player = new YT.Player('player', ...);

This of course creates the problem of leaking a global variable for whatever the id is named, which is something that I try to avoid (because it creates a loophole for strict mode and is just confusing and unexpected behavior).

A workaround is to hyphenate the name so that it can't be accessed from the global space

<div id="js-player"></div>

// now window['js-player'] is guarded from accidental access
var player = new YT.Player('js-player', ...);

but the bottom line is that using ids is just bad practice and I prefer to avoid them altogether since classes work nicely and don't have the weird side affects.

coolaj86
  • 74,004
  • 20
  • 105
  • 125

1 Answers1

13

Might be a bit late for an answer but anyways ...

Just pass the selector like so

var player = new YT.Player(
                 document.querySelector('.your-class'), 
                 ... API Stuff ...
             );

Of course, you could use jQuery or any other vanilla JS method for selecting elements.

var player = new YT.Player(
                 $('.your-class')[0], 
                 ... API Stuff ...
             );

If you use a method that returns a node list be sure to loop trough the items like so: Todd Motto - Looping Through NodeLists / Arrays

Bjørn Lindner
  • 184
  • 3
  • 11