4
\$\begingroup\$

I'm currently learning some jQuery and I am stuck on something. On a small exercise I did, I was asked to perform an action when you mouseover a div class. I gave a different solution than the one suggested and I was wondering which one is written best and why.

HTML code

<tr id ='user_1' class='datarow'>
   <td><input class='data' type='text' name='firstname' value='Firstname 1'></td>
   <td><input class='data' type='text' name='lastname' value='Lastname 1'></td>
   <td class='deletecell'><div class='success'></div></td>
</tr>

Here is my solution:

$(document).on('mouseover', '.success', function() {
    $(this).removeClass('success').addClass('delete');
});

And here is his solution:

$(document).on('mouseover', '.deletecell', function() {
    $('.success', this).addClass('delete').removeClass('success');
});

PS: Does it matter if addClass is first and removeClass is second?

\$\endgroup\$
3
\$\begingroup\$

Yours is simpler and therefore better. However, I would simplify it further as:

$('.success').on('mouseover', function() {
    $(this).removeClass('success').addClass('delete');
});

Is shouldn't matter much whether you call .addClass() first or .removeClass() first.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.