Reputation: 34
help me out with this code, I am trying to assign a class to the clicked button's child element but when I fire a click event on any one of the button that class is assigned to all buttons child elements.I have written the jquery code for it mentioned below which works, but it works when i double click on one of the buttons and also the javascript code works in console but not in my js, html files i have the js block of code in $(document).ready(function(){});
function. I need help!
Html Code:
<div class="interact-Box">
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
</div>
Javascript Code:
$(.p-emote).on('click', ()=>{
var c = $(this).children('i');
$(c).toggleClass('interacted');
});
Upvotes: 1
Views: 459
Reputation: 344
You are missing single quotes around your selector and also don't use arrow function as it changes the way you are referencing $(this) into the window object. If you switch it back to something like the code below, you will see your children. Cheers.
$('.p-emote').on('click', function () {
var c = $(this).children('i');
console.log($(this).children('i'));
$(c).toggleClass('interacted');
});
Upvotes: 1
Reputation: 2189
Use the event target (the event being the click, the target being the specific element that was clicked) by passing the event object into the callback.
$('.p-emote').on('click', (event)=>{
var c = $(event.target).children('i');
$(c).toggleClass('interacted');
});
EDIT: other answer rightly points out that you need quotes around the selector name ('.p-remote')
https://api.jquery.com/event.target/
Upvotes: 1