Jayce
Jayce

Reputation: 595

How to replace in a Html `table`, the first `th` Html tag by `td` Html tag with JavaScript

I am using jQuery-Visualize by Filament Group, Inc. which produces HTML5 canvas charts driven by HTML table elements.

A requirement of this plugin is, when using a multi-dimensional table, that the first th in the thead row tr needs to be a td.

My tables look like this:

<table>
    <thead>
        <tr>
            <th>...</th> <!--This element-->
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>...</th>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>
        ...
    </tbody>
</table>

But the plugin requires this, otherwise it adds an extra empty classification to the graph, which changes the graph layout:

<table>
    <thead>
        <tr>
            <td>...</td><!--Needs to be-->
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>...</th>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>
        ...
    </tbody>
</table>

I have an example on jsFiddle that demonstrates the issue.

How can I use Javascript/jQuery to change the table as described?

Upvotes: 1

Views: 3330

Answers (5)

dreamweiver
dreamweiver

Reputation: 6002

try this way

HTML CODE:

     <table id="Tbl">
      <tr>
       <th>Hello</th>
       <th>...</th>
       <th>...</th>
       <th>...</th>
       <th>...</th>
       <th>...</th>
      </tr>
    </table>

JQUERY CODE:

    $('th:eq(0)').replaceWith('<td>'+$('th:eq(0)').html()+'</td>');

LIVE DEMO:

http://jsfiddle.net/dreamweiver/LPzs8/6/

EDIT:corrected the code to make it more precise towards the requirement

Happy Coding:)

Upvotes: 0

JuniorCoder
JuniorCoder

Reputation: 342

You can achieve this by using jQuery. Try this code:

$(document).ready(function () {
   $("tr:first-child th").each(function() {
      $(this).replaceWith('<td>' + $(this).html() + '</td>'); 
   });
});

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

you can use like

 $(document).ready(function () {
        $("th:first").replaceWith("<td/>",{text:"....."});
    });

Upvotes: 1

Felix
Felix

Reputation: 38112

Try to use:

$('tr th:eq(0)').replaceWith(function(){
    return $("<td />").append($(this).contents());
});

or easier to understand:

$('tr th:first').each(function() {
    $(this).replaceWith("<td>" + $(this).html() + "</td>");
});

Upvotes: 3

adhie
adhie

Reputation: 284

How about:

$('tr>th').first().replaceWith('<td></td>');

Or if it doesn't work:

$('tr>th').first().replaceWith($('<td></td>'));

Upvotes: 0

Related Questions