How can I use jQuery to convert <div> into HTML table?

夙愿已清 提交于 2021-01-29 03:01:10

问题


<div> Hii,this is just an example  </div>

change to

<td>Hii, only tag will be change  </td> 

回答1:


in case someone needs to convert on the-fly:

var div2table = $('.outer-div ').map(function () {
                var issue = $(this);
                var trline = issue.find('.inner-div').map(function () {
                    return '<td>' + $(this).text();
                }).get().join('</td>');
                return '<tr>'  + trline;
            }).get().join('</tr>');

div2table = '<table>' + div2table + '</table>';

where divs are

<div class='outer-div'><div class='inner-div'>this will be 1st TD</div>.....</div>



回答2:


html div structure to table

html

    <div class='tr'>
        <div class='td'>this will be 1st TD</div>
        <div class='td'>this will be 2nd TD</div>
        <div class='td'>this will be 3rd TD</div>
    </div>
    <div class='tr'>
        <div class='td'>this will be 1st TD</div>
        <div class='td'>this will be 2nd TD</div>
        <div class='td'>this will be 3rd TD</div>
    </div>
    <div class='tr'>
        <div class='td'>this will be 1st TD</div>
        <div class='td'>this will be 2nd TD</div>
        <div class='td'>this will be 3rd TD</div>
    </div>

script

<script>
var div2table = $('.tr').map(function () {
                var issue = $(this);
                var tdline = issue.find('.td').map(function () {
                    return '<td>' + $(this).text();
                }).get().join('</td>');
                return '<tr>'  + tdline + '</td>';
            }).get().join('</tr>');

div2table = '<table>' + div2table + '</tr></table>';

console.log(div2table);
</script>

use div2table variable to print your result

Output

<table>
    <tbody>
        <tr>
            <td>this will be 1st TD</td>
            <td>this will be 2nd TD</td>
            <td>this will be 3rd TD</td>
        </tr>
        <tr>
            <td>this will be 1st TD</td>
            <td>this will be 2nd TD</td>
            <td>this will be 3rd TD</td>
        </tr>
        <tr>
            <td>this will be 1st TD</td>
            <td>this will be 2nd TD</td>
            <td>this will be 3rd TD</td>
        </tr>
    </tbody>
</table>



回答3:


You don't need to use jQuery to convert a block level element to table-cell:

div{
    display:table-cell;
}
<div> Hii,this is just an example  </div>
<div> Hii,this is just an example  </div>
<div> Hii,this is just an example  </div>
<div> Hii,this is just an example  </div>
<div> Hii,this is just an example  </div>


来源:https://stackoverflow.com/questions/40007998/how-can-i-use-jquery-to-convert-div-into-html-table

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