Check the selected class in jQuery

Question!

I have following function:

function next_or_previous(){
    $(document).on('click', 'a.next, a.previous', function (e) {
        var rh = $(this);

         if (rh == 'a.next') { //??
             console.log("next");
         } else if (rh == 'a.previous') {
             console.log("previous");
         }
    });
};

I simply want to check what class (next or previous) was clicked. How would I go about doing this?

By : steve Kim


Answers

can use hasClass() or is()

if (rh.hasClass('next') ){...

if you only have 2 selectors you shouldn't really need to check in the else



Use hasClass() function.

function next_or_previous(){
        $(document).on('click', 'a.next, a.previous', function (e) {
           var rh = $(this);
           if (rh.hasClass('next')){ //??
                console.log("next");
           }else if (rh.hasClass('previous')){
                console.log("previous");
          }
      });
   };


There is a way if the first element is the only one to start with that character:

$ a=(asd fgh ijk)
$ echo "${a[@]^[!${a:0:1}]}"
asd Fgh Ijk

This extracts the very first character of the first element, then excludes that character from being uppercased; [!${a:0:1}] expands to [!a], which matches only f and i as the first characters of their elements.

It fails if multiple elements start with the same character, though:

$ a=(asd agh ijk)
$ echo "${a[@]^[!${a:0:1}]}"
asd agh Ijk


This video can help you solving your question :)
By: admin