0

How to get a specific class value from element div?

Simple HTML

<h4>THE CLASS NAME FROM THIS DIV IS: 'class1 class2'</h4>
<p id="result-class"></p>

Simple jQuery

var classFormDiv = $('.class1').attr('class');

$('#result-class').html('result=> ' + classFormDiv);

See, https://jsfiddle.net/FIERMANDT/tbqLcx32/

My answer 21 Jul 2020

var elDiv = document.getElementById('get-class');

function getClassVal(element, classNameOrIndex) {
  var listClass = element.classList;
  var classValue = '';
  
  switch(typeof classNameOrIndex) {
    case 'string':
      for(var i = 0; i < listClass.length; i++) {
        if (listClass[i] === classNameOrIndex) {
          classValue = listClass[i];
        }
      }
      break;
      
    case 'number':
      classValue = listClass[classNameOrIndex];
      break;
      
    default:
      classValue = listClass.value;
      break;
  }
  
  return classValue;
}

console.log( getClassVal(elDiv, 'class-foo') );
<div id="get-class" class="class-foo classic">This element have two class 'class-foo' and 'classic'</div>
Firmansyah
  • 106
  • 12
  • 27

2 Answers2

2

var classFormDiv = $('.class1').attr('class').split(' ')[0]; Try this

Durga
  • 15,263
  • 2
  • 28
  • 52
1

use with split() like this classFormDiv.split(" ")[0] this [0] will take the firstclassName .Take the classname as your wish from array(see the console.log)

var classFormDiv = $('.class1').attr('class');

$('#result-class').html('result=> ' + classFormDiv.split(" ")[0]);

console.log(classFormDiv.split(" "))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>How to get Class from This DIV? Just one class I want to take</h4>
<div class="class1 class2"></div>

<h4>THE CLASS NAME FROM THIS DIV IS: 'class1 class2'</h4>
<p id="result-class"></p>
prasanth
  • 22,145
  • 4
  • 29
  • 53