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?
Getting the Last Character from String If you want to retrieve the last character from String then you can call charAt(length -1) where length is the length of a given String. For example, if the given String is "Avengers" then "Avengers".
Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.
Using The id Attribute The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id. The syntax for id is: write a hash character (#), followed by an id name.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With