How to add a class via jQuery where the class has no name

374 views Asked by At

In jQuery, how do I select and add a class to a class when the class does not have a value?

Here is some example code:

<div class="">
  <div class="">
    <span class=""><i class=""></i></span>
    <div class="">
      <span class=""></span>
      <span class=""></span>
    </div><!-- /.info-box-content -->
  </div><!-- /.info-box -->
</div>

If I only have the above code, how can I achieve the following code by using jQuery:

<div class="col-md-3 col-sm-6 col-xs-12">
  <div class="info-box">
    <span class="info-box-icon bg-aqua"><i class="fa fa-envelope-o"></i></span>
    <div class="info-box-content">
      <span class="info-box-text">Messages</span>
      <span class="info-box-number">1,410</span>
    </div><!-- /.info-box-content -->
  </div><!-- /.info-box -->
</div>

I know that jQuery has the addClass() function, yet I am not sure how to use this when the class I wish to add to does not have a class value.

Is there a specific jQuery technique that I should be using?

Thanks

2

There are 2 answers

0
sam On BEST ANSWER

Can you add IDs to your elements?

Then you can do $('#element').addClass('info-box') etc

5
choz On
$(function() {
    $("div[class='']").each(function(i){
        switch (i) {
            case 0:
                $(this).addClass("col-md-3 col-sm-6 col-xs-12");
                break;
            case 1:
                $(this).addClass("info-box");
                break;
            case 2:
                $(this).addClass("info-box-content");
                break;
            default:
                $(this).addClass("yawn");
                break;
        }
    });
});

This is how you call the non-value class of an element in jquery.

$("div[class='']").addClass("test");

or at least, that's how i can come up with.

http://jsfiddle.net/mikeill/4keypu23/1/