0

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?

0

1 Answer 1

2

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.

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

6 Comments

This partially answer my question for applying the wrapper class. But how do I dynamically remove the existing old classes in <table>, and inject the class="table table-bordered table-condensed" inside the <div class="content-entry">? I've modified the original question with a more detailed example.
Another question regarding to .wrap, does the order of the matched classes matter?
No, It is just a selector like all other selectors.. You have the option of .addClass and .removeClass to deal with classes..
Your code works for the specific instance of class="old-style". I might have multiple classes, is there a way I can globally remove all classes of the <table>elements enclosed in <div class="content-entry"> and apply the new classes throughout? I might have multiple table blocks and each may have different default class/attributes.
Updated post will help!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.