How to select and get attributes of video and audio element while iterating through DOM in jQuery

Viewed 260

I tried this for given html element.

    $('#dynamicformdata').each(function() {

          console.log(this.type);
     })

  <div id="dynamicformdata">
    <video width="320" height="240" >
        <source src="movie.mp4" type="video/mp4">
        <source src="movie.ogg" type="video/ogg">

   </video>
 </div>

How to get all attribute of this video tag inside div.

1 Answers
    $('#dynamicformdata').each(function() {
      // "this" in the first function refers to the div
      console.log(this);

      // call a second function for every source tag in every video in the dynamicformdata tag
      $('video>source', this).each(function() {
        // "this" referes to a source tag
        console.log(this.type);
      });
    });

If you want to get all types as an array:

    $('#dynamicformdata').each(function() {
      var types = [];
      $('video>source', this).each(function() {
        types.push(this.type);
      });
      // logs the div element and all found types (duplicates not filtered out)
      console.log(this, types);
    });
Related