2

This is a simple div with two classes:

<div class="social twitter"></div>

I am trying to get the name of the second class onclick:

$( ".social" ).bind( "click touchstart", function() {
        var sn = $(this).**SECOND_CLASS(= twitter)**;

    });

any ideas on how this could be done? Thank you

2 Answers 2

5

May help you can use this code if you have just one space between classes

$( ".social" ).on( "click touchstart", function() {
        var sn = ($(this).attr('class').split(' '))[1];
         alert(sn);
    });

DEMO

and if you have more spaces between classes you can use .. and I think it will be better

$( ".social" ).on( "click touchstart", function() {
        var sn = ($(this).attr('class').replace(/\s+/g, ' ').split(' '))[1];
         alert(sn);
    });

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

@Rossitten you welcome .. Good Luck :) .. I just tried to searching for something right now the if you have more than one space between classes .. I find the answer .. I will update the code
4

You can use classList which will return list of class attributes of the element.

$(".social").bind("click touchstart", function() {
  var cName = this.classList[1];
  alert(cName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="social twitter">Hello</div>

Fiddle Here

1 Comment

Never go away from Vanilla JS, it makes life easier.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.