Как я могу использовать jQuery для преобразования <div> в таблицу HTML?

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

изменить на

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

2 ответа

HTML структура div в таблицу

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

использовать div2table переменная для печати вашего результата

Выход

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

Если кому-то нужно конвертировать на лету:

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>';

где дивы

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

Вам не нужно использовать jQuery для конвертации block элемент уровня до 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>

Другие вопросы по тегам