Get last character from id attribute

I need to get the last character of the element identifier and use it to find another element by id on the same page.

What I have tried so far:

$(".spoilerButton").each(function(){
        $currentId=($this).attr("id").slice(-1);
        $hiddenContent=$("#spoiler"+$currentId);
        $this.click(function(){
                $hiddenContent.toggle(500);
        });
});

In principle, each element of the spoilerButton class with the identifier spoilerButtonN, where N is an integer, has a corresponding element with id spoilerN, which should be displayed / hidden after it is clicked.

The code does not seem to start the part $currentId=($this).attr("id").slice(-1);where I am trying to get the last character (N) from the spoilerButton id.

What is the right way to do this?

+4
source share
1 answer

You have your partners in the wrong place:

$currentId=$(this).attr("id").slice(-1);
// Note     ^    ^

, , , id, $(this).attr("id") - this.id, :

$currentId=this.id.slice(-1);

... , , , id.

+12

Source: https://habr.com/ru/post/1539623/


All Articles