@Barmar has answered this from a code perspective. Let's see about helping pass some knowledge on. There are some non-code concepts that will help you avoid this problem in the future.
This is a common, and very frustrating, mistake with understanding how JavaScript and HTML work together. The JavaScript doesn't full "belong" to the h2 element when you put it in the onclick attribute, it just runs when you click it. The JavaScript can touch anything in the rest of the page. That's why $('h2').removeClass()
is selecting every h2
element.
In general, you should do a few things to help your confusion.
- Put your JavaScript in script blocks, or better yet separate
files, not inside HTML elements.
- Use jQuery to only deal with the
one
h2
at a time (as Barmar suggested).
- Do some reading how how jQuery selectors work. jquery.com documentation is very good, it will be time well spent.