Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last character from id attribute

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?

like image 817
hytromo Avatar asked May 07 '14 17:05

hytromo


People also ask

How do I get the last character of a string?

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".

How to get the last character of string in JavaScript?

Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.

How do I get the last character of a string in jquery?

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.

How to refer to an id in HTML?

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.


1 Answers

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.

like image 71
T.J. Crowder Avatar answered Sep 26 '22 02:09

T.J. Crowder