KDX
KDX

Reputation: 619

How to dynamically modify CSS class using Javascript / jQuery with wrapper?

I have an existing html code of table.

eg.

<div class="content-entry">
    <table class="old-style" border="3">
        <tr align="middle">
            <td style="font-weight:bold"></td>
        </tr>
    </table>
</div>

I would like to conditionally remove all attributes/classes of the current table with the injection of a wrapper <div> and apply css class style to override the existing table behavior using Javascript / jQuery.

conten-entry might have multiple table blocks, and I would like to apply the same style change to all of them.

to:

<div class="content-entry">
    <div class="responsive-table">
        <table class="table table-bordered table-condensed">
            <tr>
                <td></td>
            </tr>
        </table>
    </div>
</div>

How can I do this without changing the original html code?

Upvotes: 0

Views: 247

Answers (1)

Rayon
Rayon

Reputation: 36609

Use .wrap, wraps an HTML structure around each element in the set of matched elements

$('.old-style').wrap('<div class="responsive-table"></div>').removeClass().addClass('table table-bordered table-condensed');
.responsive-table {
  color: red;
}
.table {
  font-weight: bold;
}
.table-bordered {
  border: 2px solid black;
}
.table-condensed>tbody>tr>td,
.table-condensed>tbody>tr>th,
.table-condensed>tfoot>tr>td,
.table-condensed>tfoot>tr>th,
.table-condensed>thead>tr>td,
.table-condensed>thead>tr>th {
  padding: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="content-entry">
  <table class="old-style">
    <tr>
      <td>Hello</td>
    </tr>
  </table>
</div>

Note: Calling .removeClass with no arguments will remove all of the item's classes.

Upvotes: 2

Related Questions