Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
How to reconcile 'this' referencing DOM element and 'this' referencing class?

I'm having an issue understanding how I might go about using the 'this' keyword to refer to a DOM element that is has been clicked, but also using that inside a class where 'this' usually refers to the instance of that class.

Here's a snippet of the relevant code:

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }
  
  selectButton() {
    $(this).toggleClass('selected');
    this.columnController();
  }
  
  columnController(){
    // A function that does something else
  }
}

The issue I'm having is that it doesn't recognise columnController() as a function. I imagine this is because of the scope and how it works with 'this', but I'm not sure how to proceed.

In the above code, selectButton() is successfully applied to all the buttons specified, but the error is given on this.columnController(). Exact console error is:

Uncaught TypeError: this.columnController is not a function

Thank you in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't use this to represent both objects, so pick one and get the other one through some other mechanism.

For example: Use an arrow function to bind the this value to the class, then get the element from the event object.

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }

  selectButton = (event) => {
    $(event.currentTarget).toggleClass('selected');
    this.columnController();
  }

  columnController() {
    console.log("this runs");
  }
}

new Passwords();
.selected {
  background: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="password-column">
  <button class="steel-button">click</button>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!