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

4.5k views Asked by At
<div> Hii,this is just an example  </div>

change to

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

There are 3 answers

2
Roko C. Buljan On

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>

1
yob On

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>
1
Ishtiaq Ahmed On

HTML div structure to the table

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 border="1">' + div2table + '</tr></table>';
$('#table-container').html(div2table);
console.log(div2table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Div structure</p>
<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>
<p>After js execution, it will convert to Table</p>
<div id="table-container">

</div>

use the 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>