Home > Blockchain >  How to have a function tell whether to apply on "this" or other element ID
How to have a function tell whether to apply on "this" or other element ID

Time:11-16

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?

CodePudding user response:

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>  
 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related