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

223
Views
How to have a function tell whether to apply on "this" or other element ID

I have a function like this:

function toggle(me, style) {
  var myelm = me == '' ? this : document.getElementById(me);
 
  myelm.classList = style; 
}

I want the function to know when it has to apply the style to the triggering element or to some other element like in the following examples:

 <div onclick="toggle(this);"></div> <!--this function should apply to this element only-->
 <div onclick="toggle('otherelement');"></div> <!--this should apply to other element of the DOM-->

but it only works when the ID is specified, and wont apply on this as intended. What is wrong?

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

0

In the first case you pass a DOM element, in the second a (non-empty) string. So the condition me == '' that you check is not true in either case. Secondly, this is irrelevant in the function, since you never call it with a this binding (a this binding is not the same thing as passing this as argument).

You'll want to check the data type of the argument, and when it is a string, retrieve the DOM element, and otherwise just use the argument that was given (me) -- not this:

Another thing: you need to call the toggle method on the classList property:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}

NB: make sure to also pass the second argument (style)!

Snippet:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}
.highlight { background: yellow }
<div id="otherelement">This is other element</div>

<p></p>

<div onclick="toggle(this, 'highlight');">toggle this</div>
<div onclick="toggle('otherelement', 'highlight');">toggle other element</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!