How can I use a class instead of id for new YT.Player()
Asked Answered
A

1

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.

Abolish answered 31/7, 2015 at 21:33 Comment(0)
R
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

Richelle answered 19/3, 2017 at 12:31 Comment(2)
The link is deadHomologue
Edit: Updated example link.Acknowledgment

© 2022 - 2024 — McMap. All rights reserved.