I have the following html.
<div>
<img class="foo">
<a href="#" onClick="changeImage(this, param1, param2)">sth</a>
</div>
I want to change the class of image (remove foo, add bar) when user clicks on the link. However, I cannot write down the right selector for jquery.
I am also not sure if I really need to pass the this to the function.
function changeImage(link, param1, param2) {
//Following line does not work
$(link).parent('div img').removeClass("foo").addClass("bar");
}
You also don’t need to pass -this- into your onclick, we’re not even effecting it in the function, and we can grab it regardless.
On a side note: Try to never use any onclick/onmouseover/etc events on any DOM elements, each one individually creates a script block within legacy browsers (IE), and with hundreds/thousands of elements on a page, it can deteriorate performance.
Use
.click(),.on(), whatever version of jQuery you supports version instead.