8
<td>
<input type="radio" value="5" name="Form1a1" class="abobrinha Form1comentarioA" />
</td>
I have 2 classes inside in my radio input, in jQuery I would like to select only the last class (which in my case is the second)
8
<td>
<input type="radio" value="5" name="Form1a1" class="abobrinha Form1comentarioA" />
</td>
I have 2 classes inside in my radio input, in jQuery I would like to select only the last class (which in my case is the second)
8
$(":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 splitter;[1]
- obtains the second member of the collection.Source:
ONLY ORIGINAL, 'How to get the Second class name from element?'
+1 for being faster :P
8
The quickest I could think of is to use the method 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>
<input type="radio" value="5" name="Form1a1" class="abobrinha Form1comentarioA" />
In the example we are:
class
;
;1
of the matrix resulting from step 2.If the idea is to take the last class, instead of taking the entrance 1
of the resulting matrix, we can skip to the end of the same using the method .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>
<input type="radio" value="5" name="Form1a1" class="abobrinha algumaCoisaMais Form1comentarioA" />
+1 for also being a correct answer ;)
7
The other answers refer well to doing this with jQuery. Actually you don’t need jQuery for that. 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 classes of the element. Selecting position 1 gives the second class (because arrays start index at zero).
Here we have our Vanillajs booming :)
Very good the VJS thing.
Browser other questions tagged javascript jquery
You are not signed in. Login or sign up in order to post.
I don’t quite understand what you want... do you want to know what the second class of that element is? you can explain more about what you are doing and needs that functionality?
– Sergio
What do you mean? You do not select classes with jQuery, you select elements (in this case the input).
– bfavaretto
@chocolatemontana any of the answers solved your question? If yes it is important to mark the correct answer.
– gmsantos