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?
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?
Share Improve this question asked May 7, 2014 at 17:13 hytromohytromo 1,5312 gold badges29 silver badges57 bronze badges 4-
You don't seem to define $this. And it would be simpler to do ̀
this.id.slice(-1)
– Denys Séguret Commented May 7, 2014 at 17:14 -
1
I don't think it's generally a remended practice to prefix all your variable names with
$
. – JLRishe Commented May 7, 2014 at 17:15 -
Right. If there's any convention, it's that
$var
should be a variable containing a jQuery object, e.g.$this = $(this)
. – Barmar Commented Jun 10, 2014 at 17:53 -
You should also declare local variables with
var
. You're setting global variables$currentId
and$hiddenContent
, which is not desirable. – Barmar Commented Jun 10, 2014 at 17:54
1 Answer
Reset to default 15You 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
.