0

Here's the "almighty code"!

function testFun(target){
  $(this).addClass("element")
  $(target).addClass("target")
}
 
<a href="#" onclick="testFun('.class')" >Element</a>
<div class="class"> </div>

Briefly, upon the onClick event I want to modify the element too! I want to be able to use the same function in multiple situations. Please provide a solution to be able to do the above mentioned.

1 Answer 1

1

The issue is because this in your testFun() function does not reference the element that called the function - you need to pass in the reference of this:

function testFun(element, target) {
  $(element).addClass("element")
  $(target).addClass("target")
}
.element {
  color: red;
}
.target {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="testFun(this, '.class')">Target</a>
<div class="class">Target</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Is there not a way of using only one parameter?
Not using an onclick attribute, no. If you want to pass the this reference to the event handler function you could instead attach your event with Javascript.
Your code did the trick, I was only attempting to reach the same thing using only one argument. The way you showed me is the way i originally did it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.