Reputation: 1531
I need to get the last character of the id of an element and use it in order to find another element by id in the same page.
What I've tried so far:
$(".spoilerButton").each(function(){
$currentId=($this).attr("id").slice(-1);
$hiddenContent=$("#spoiler"+$currentId);
$this.click(function(){
$hiddenContent.toggle(500);
});
});
Basically, every element of class spoilerButton with an id of spoilerButtonN where N an integer, has a corresponding element with id spoilerN that needs to show/hide, once it is clicked.
The code does not seem to run the $currentId=($this).attr("id").slice(-1);
part, where I try to get the last character (N) from the spoilerButton's id.
What is the correct way to do it?
Upvotes: 6
Views: 7434
Reputation: 1074138
You have your parens in the wrong place:
$currentId=$(this).attr("id").slice(-1);
// Note ^ ^
Or of course, specifically with respect to the id
attribute, $(this).attr("id")
is just a long way to write this.id
, so:
$currentId=this.id.slice(-1);
...but that's not true for all attributes, just certain reflected ones like id
.
Upvotes: 15