Reputation: 8457
I have a music page set up and when the play button is clicked for a song, the class changes from buttons_mp3j
to buttons_mp3jpause
. When the class is buttons_mp3jpause
, I want to target its parent li.song
and add a class to it.
<li class="song">
<div>
<span>
<span class="buttons_mp3jpause">
</span>
</span>
</div>
</li>
I have tried the following code but it didn't work.
$(".buttons_mp3jpause").parents("li.song").addClass("playing");
Where did I go wrong?
Edit
$('.haiku-play').bind('click', function() {
$('.haiku-player').jPlayer("pause");
})
Edit 2
<article>
<ul>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
</ul>
</article>
<article>
<ul>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
</ul>
</article>
<article>
<ul>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
<li class="song">yadayada</li>
</ul>
</article>
Upvotes: 0
Views: 94
Reputation: 20250
As you mentioned in the question, you're assigning the class buttons_mp3jpause
dynamically, so you need to attach a handler to an element which exists in the DOM on page load, and delegate it to the dynamic class, using jQuery's .on()
:
$('.song').on('click', '.buttons_mp3jpause', function() {
$(this).closest('li.song').addClass('playing');
});
Simply remove the playing
class from all other song
elements (the below presumes that all of your song
elements are siblings
!):
.addClass('playing').siblings('li.song').removeClass('playing');
The easiest thing in this situation would be to simply remove the playing
class from all song
elements, and then just add it to the relevant one:
$('li.song').removeClass('playing');
$(this).closest('li.song').addClass('playing');
$('.song').on('click', '.buttons_mp3jpause', function() {
$('li.song').removeClass('playing');
$(this).closest('li.song').addClass('playing');
});
Upvotes: 2
Reputation: 10967
$(".buttons_mp3jpause").parent().parent().parent().addClass("playing");
If you want to target the parent.
$(".buttons_mp3jpause").closest("li.song").addClass("playing");
Or you can use closest to find the closest li with class song
Upvotes: 0