0

I want to execute a function to remove the styling in one of my tables when a button with id reset is clicked and on using jquery selectors, I am unable to do so with the following code

$('#reset').on('click', function(){
  $('td').removeAttr('style');
});

But it works when I put it like this

$('body').on('click', '#reset', function(){
  $('td').removeAttr('style');
});

What am I doing wrong in the id selection.

t.niese
  • 32,069
  • 7
  • 56
  • 86
  • 1
    Probably because the element doesn't exist at the time you run the first code. See [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – charlietfl Aug 25 '18 at 12:45
  • Also see [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – charlietfl Aug 25 '18 at 12:46
  • Hi Utkarsh, I think your code will work if you change `$('td').removeAttr('style');` to `$('td').removeAttr('class');` Check this link [enter link description here][1] [1]: https://jsfiddle.net/xpvt214o/678247/ – simplelenz Aug 25 '18 at 12:53
  • @simplelenz the question is not about that `removeAttr` is not working, but `$('body').on('click', '#reset',` does and `$('#reset').on('click',` does not. – t.niese Aug 25 '18 at 12:54
  • @charlietfl got it. Thanks! – Utkarsh Kumar Aug 25 '18 at 12:58

0 Answers0