Search code examples
javascriptjqueryhtmlmp3html5-audio

Access to repetitive tags in jQuery


So I've got this piece of HTML (it's mp3 player):

<div id="player-body_0" class="player-body">
    <audio id="player_0" class="player">
        <source src="http://www.noiseaddicts.com/samples_1w72b820/2543.mp3" type="audio/mpeg" />
    </audio>

    <div id="audio-player_0" class="audio-player">
        <div id="controls_0" class="controls">
            <i id="play_0" class="fa fa-play play"></i>
            <span id="start-time_0" class="time start-time">00:00</span>
            <div id="progressbar_0" class="progressbar"></div>
            <span id="time_0" class="time">00:00</span>
            <i id="mute_0" class="fa fa-volume-up mute" onclick=""></i>
            <div id="volume_0" class="volume"></div>
        </div>
    </div>
</div>

code is automatically generated, so I could have 30+ players like this all on the same website. Ids in tags of course will increment in every next player-body. How could I manage all this players with generic methods in jQuery? To manage player mute button I could have something like this:

var mute_button = $('.mute'); 
var player = document.getElementById('player_0');

mute_button.click(function() {
    $(this); //clicked mute button
    //how to easily access proper audio tag without using its id?
});

But how in above function I could access audio player tag without using its id? As I said I want methods to be generic I can't just repeat them like 30+ times.


Solution

  • From the .mute icon... Lookup for the parent matching the .player-body... Then lookdown, using .find(), for the <audio> tag using the .player class...

    You now have the target element!

    Then simply mute it... Okay... You need the DOM element, not the jQuery object. But you have it using [0] against a jQuery object because the DOM element is the first property.

    Concretely, it's a one liner:

    $('.mute').on('click', function(){
        $(this).parents(".player-body").find(".player")[0].muted = true;
    });
    

    That is what's called "traversing" DOM elements...
    You just have to know a couple jQuery methods to navigate. ;)