<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)
<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)
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:
class
attribute;
; 1
of the resulting matrix from step 2. 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" />
$(":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? '
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).