Joseph Thomas
Joseph Thomas

Reputation: 157

Convert Multiple Tables into Sections

I am trying to convert the HTML of a basic table into a basic <section> tag. I am having trouble iterating each table, and the "content" div is being repeated into each section. See my fiddle:

$(document).ready(function() {
    var section = $("<section>");
        $("table").each(function(){
            $("td").each(function(){
                var content = $('<div class="content">').html(this.innerHTML);
                section.append(content);
            });
        $("table").replaceWith(section);  
    });
});

http://jsfiddle.net/zre0qof1/

The results I need is:

<section>
<div class="content">
<h2>About</h2>
</div>
</section>

<section>
<div class="content">
<h2>Services</h2>
</div>
</section>

I know it's probably really easy and just a matter of iterating the sections/tables correctly, but I just can't seem to get it right. Thanks in advance!

Upvotes: 0

Views: 29

Answers (1)

Talya S
Talya S

Reputation: 754

From your example I understand that each table turns into
<section><div class="content"> ALL TABLE CONTENT </div></section> You only have one TR and one TD in each table, so it's hard to tell if you want something else.

If this is the case this code does the trick:

$(document).ready(function() {
    $("table").each(function(){ // go through every table
        var content = $('<div class="content"></div>'); // create a content div
        $("td", this).each(function(){ // go through every TD in table
            content.append(this.innerHTML); // insert TD content into content div
        });
        $(this).replaceWith($('<section></section>').append(content)); // put content div in section and replace this table with it
    })
});

Here's the fiddle: http://jsfiddle.net/jtw97u1f/5/

I looked it up and when creating elements you should include the closing tag, so I changed it to $('<section></section>'). Here's the answer I used as reference: https://stackoverflow.com/a/6555916/5297207

Upvotes: 1

Related Questions