Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Save access to this scope

I have color stored in a data attribute on my button that I wanted to use in a toggle. However, when I tried to access the data information using this, no data was available. How can I keep my access to the correct this scope?

I was trying to only toggle the given color for the elements which didn't contain Skip.

html

<div>
 <input id="toggleButton" type="button" value="Toggle" data-color="Red" />
</div>
<div id="toggleSet">
<div>Element</div>
 <div>Skip</div>
 <div>Element</div>
</div>

css

.ActivateRed{ color: red; }

js

$('#toggleButton').click(function(){
 $("#toggleSet div").each(function(index,element){
  if( element.innerHTML != "Skip" ){
   $(element).toggleClass("Activate"+$(this).data("color"));
                                       //^this has no data to access?
                                       //Why am I getting undefined?
  }
 });
});

Here is a jsFiddle of my attempt. I keep getting Activateundefined as the class name. Why isn't this accessing my toggleButton's data?

Answer*

Cancel