0

Is it possible to get a class as a string from multiple class in an html element.I have many classes which stored in an html element but I want to get only class name from them.

Here is my html:

<div class="class1 class2 class3 class4"></div>
<div class="class1 classb classv classd"></div>
<div class="class1 classw classdf classl"></div>
<div class="class1 classl classo classj"></div>

jquery:

<script>
     $(document).ready({

             if($(".class1").hasClass("classw")){ 
                 var cl = $(".classw").attr('class');
                 console.log(cl)// out put: class1 classw
             }
      });
</script>

As above code I will get class1 classw class But i want to get only classw class of them.

Please help

10
  • I have already it you can check in if conditional Commented Feb 16, 2016 at 4:05
  • 2
    As you've checked element class using hasClass, why not directly use classname as string Commented Feb 16, 2016 at 4:06
  • used as string? before used we have to find it right and then will to initial to a variable right? I find more tutorial if we want to get a class string we I have to used attr in jquery so how to used as string as u said? Commented Feb 16, 2016 at 4:09
  • How you found the particular class name. If you don't know the classname? Commented Feb 16, 2016 at 4:11
  • Possibly duplicate stackoverflow.com/questions/9051948/… Commented Feb 16, 2016 at 4:11

1 Answer 1

1

Not exactly sure what you are trying to do, but this will get you all the classes for each element:

<div class="class1 class2 class3 class4"></div>
<div class="class1 classb classv classd"></div>
<div class="class1 classw classdf classl"></div>
<div class="class1 classl classo classj"></div>

$('div.class1').each(function() {
    console.log( $(this).attr('class').split(' ') )
})

Then you can do an indexOf on the arrays that are returned:

https://jsfiddle.net/nebulousal/y8yoofd4/1/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.