d
Amit DhamuSoftware Engineer
 

Select Nth Class of Element

1 minute read 00000 views

If you have an element which has multiple classes and you want to get the 3rd for example, simply executing $('#element').prop('class') will not be enough as that will give you all class names in one string.

Instead, you can use the following function.

function getClassByN(element, n) {
  return $(element).prop('class').split(' ')[n]
}
<div id="notepad" class="right box rounded">My container with 3 classes</div>
var first_class = getClassByN('#notepad', 0)
var second_class = getClassByN('#notepad', 1)
var third_class = getClassByN('#notepad', 2)