The problem is that you're only attaching the click event listener to the elements with a class of .profile_card
. Since the first element doesn't have a class of .profile_card
initially, the click event isn't attached to it.
Without changing any HTML, the easiest way to work around this would be to delegate the click event to a common ancestor so that the class will be checked when the click event is fired (rather than when the event is initially attached like before):
Updated Example
$('.profiles_container').on('click', '.profile_card', function() {
// ...
});
Alternatively, you could also just attach the event listener to all the children elements regardless of their classes:
Updated Example
$('.profiles_container').children().click(function() {
// ...
});
However, the better approach would be to use a common class between the elements and then add an .is_selected
class in addition to the common class. In doing so, the event listener will be attached to all the elements initially:
Updated Example
$('.profile_card').on('click', function() {
$('.profile_card').removeClass('is_selected');
$(this).addClass('is_selected');
});
Updated HTML:
<div class="profiles_container">
<div class="profile_card is_selected">
Default
</div>
<div class="profile_card">
First
</div>
<!-- ... -->
</div>