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

拟墨画扇 提交于 2019-12-12 04:28:42

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36950368/how-to-dynamically-modify-css-class-using-javascript-jquery-with-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!