Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>  
 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading