How to get only the second class with Jquery?

7
<td>
    <input type="radio" value="5" name="Form1a1" class="abobrinha Form1comentarioA" />
</td>

I have 2 classes inside in my input radio, in jQuery I would like to select only the last class (which in my case is the second)

    
asked by anonymous 15.07.2015 / 20:41

3 answers

7

Pick up the second class

The quickest thing that occurred to me is to use split() :

$('input[name="Form1a1"]').attr('class').split(' ')[1];

Example:

$(function() {
  alert($('input[name="Form1a1"]').attr('class').split(' ')[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><inputtype="radio" value="5" name="Form1a1" class="abobrinha Form1comentarioA" />

In the example we are:

  • Catch the contents of the class attribute;
  • Subsequently manipulating the string by leaving it with whitespace ;
  • Finally we only get the input 1 of the resulting matrix from step 2.
  • Catch the last class

    If the idea is to get the last class, instead of getting the input 1 of the resulting array, we can jump to the end of it using the .pop() :

    $('input[name="Form1a1"]').attr('class').split(' ').pop();
    

    Example:

    $(function() {
      alert($('input[name="Form1a1"]').attr('class').split(' ').pop());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><inputtype="radio" value="5" name="Form1a1" class="abobrinha algumaCoisaMais Form1comentarioA" />
        
    15.07.2015 / 20:51
    7
    $(":radio[name='Form1a1']").attr('class').split(' ')[1]
    

    Explanation:

    • $(":radio[name='Form1a1']") - gets the list of all Radiobuttons that have the attribute name equal to Form1a1 ;
    • .attr('class') - gets the value of the 'class' attribute;
    • .split(' ') - transforms the string into an array of strings, using whitespace as a divider;
    • [1] - gets the second member of the collection.

    Source:

    Original SO, ' How to get the second class name from element? '

        
    15.07.2015 / 20:49
    6

    The other answers refer well to doing this with jQuery. Actually you do not need jQuery for this. It can be done with native JavaScript like this:

    var segundaClasse = document.querySelector('input[type="radio"]').classList[1];
    

    The .classList is an array with all element classes . Selecting position 1 gives the second class (because the arrays start indexing at zero).

    example: link

        
    15.07.2015 / 21:10