Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first class from an element with jQuery

How can I retrieve only the first class p7 from this HTML element?

HTML

<div id="myDIV" class="p7 nextclass class_tt">some content</div>

JavaScript

$('#myDIV').attr('class').first(); //will not work
like image 983
Peter Avatar asked Dec 09 '22 09:12

Peter


2 Answers

$('#myDIV').attr('class').split(' ')[0];

$('#myDIV').attr('class') returns a string. split(' ') breaks into an array, using ' ' as a delimiter.

like image 72
Rocket Hazmat Avatar answered Jan 01 '23 08:01

Rocket Hazmat


You can use split() to do that:

var firstClass = $('#myDIV').attr('class').split(' ')[0];
like image 31
Frédéric Hamidi Avatar answered Jan 01 '23 10:01

Frédéric Hamidi