28

I am trying to use a button to start a track in an HTML5 audio tag using jQuery, but I keep getting an error.

var song = $('#audio');

$('#play').click(function() {
song.play();
});

When I use document.getElementById('audio'), it works, but when using the jQuery selector I get the following error:

Uncaught TypeError: Object [object Object] has no method 'play'

Thanks for any help.

user699242
  • 1,833
  • 4
  • 21
  • 31

3 Answers3

60

Try getting the native DOM element as jQuery knows nothing about .play method on the wrapped array returned by the $('#audio') selector:

song.get(0).play();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    That worked...why? Could you give a brief explanation, just so I understand. Thanks!! – user699242 Jul 05 '11 at 21:15
  • 7
    @user699242, when you use `$('..some selector..')` this returns an array of actual DOM objects matching your selector. The .play method is a native HTML5 method that you need to invoke on the actual native DOM element. So you need to fetch this native DOM element from the array which is returned by the jQuery selector. And because you are using an id selector (`#audio`) we can assume that there is a single element in your DOM matching this selector so we can safely use `.get(0)` to fetch it. So basically when you use `$(...)` you can invoke only jQuery functions on the result and `play` is not – Darin Dimitrov Jul 05 '11 at 21:18
  • It really help. However, why it report an undefined error when use .get(0).tagName? – panda May 12 '12 at 04:53
13

You can also write it like song.trigger('play');. That will allow you to use the $('#audio'); selector.

Cole Garstin
  • 388
  • 3
  • 9
3

Instead of .get() just use object notation:

var song = $('#audio');

$('#play').click(function() {
    song[0].play();
});

It's less to type :)

sidonaldson
  • 24,431
  • 10
  • 56
  • 61