Reputation: 253
I have a CSS rule for hiding elements with a class="hidden" and I'm using jQuery to toggle this class on and off on whatever ID i click on so I can make elements disappear.
Why does this not work?
$(this).attr('id').toggleClass("hidden");
but this does?
var x = "#" + $(this).attr('id');
$(x).toggleClass("hidden");
I know that the id is being taken correctly on the first example, but it seems that to toggle the class I have to add a "#". I haven't seen any examples of others having to resort to this so I'm wondering what madness I have here.
Many thanks
Upvotes: 0
Views: 42
Reputation: 32511
.attr('id')
returns a string, not an element.
Let's pretend your element has an ID of myThing
. Here's what your code translates to:
// 1
"myThing".toggleClass("hidden");
// 2
var x = "#myThing";
$("#myThing").toggleClass('hidden');
But really, if you're getting the ID from this
, there's no reason to extract the ID in the first place. Just use this
directly.
$(this).toggleClass('hidden');
Upvotes: 1
Reputation: 22911
You can simply use:
$(this).toggleClass("hidden");
$(this)
is the actual element you're working with, so you can use this to directly toggle classes with.
In your examples, $(this).attr('id')
is a string, and not an element.
This code works, because you're taking the ID (As a string), and selecting the ID on the webpage.:
//Store the id into a string
var x = "#" + $(this).attr('id');
//Pass the ID back into jQuery, and find the element
$(x).toggleClass("hidden");
Upvotes: 0
Reputation: 16587
$(this).attr('id').toggleClass("hidden");
You are chaining events here. $(this).attr('id')
already returns you a string. So you are technically doing "someid".toggleClass("hidden")
which doesn't makes sense.
In your second example, you are actually selecting the same element again via id and firing your method, which is right
Upvotes: 1