Search code examples
javascripthtmld3.jstableheader

Append Image to Existing Table Header


I have created a table, and I would like to add an image to the header. I am using a library called D3.js to create the table. The code is as follows:

var columns = [
    {src:"http://iconbug.com/data/3a/256/77c71e95885bf94c06c7c68ccb63b131.png"}, 
    {src:"http://iconbug.com/data/3a/256/9f8cd17bf12b1667d6c4b31b889b3034.png"}, 
    {src:"http://iconbug.com/data/b4/256/4ece97792658df143eb693c23bb991f3.png"}
];

var table = d3.select("body").append('table');
var thead = table.append('thead');

thead.append('tr')
    .selectAll('th')
    .data(columns)
    .enter()
    .append('th')
    .append('img')
    .attr('src', function(d) {
        return d.src;
    });

This code is from my related D3 post:

D3 Method of Appending Images to a Table Header

The code is mostly for context, I'm interested in how native HTML deals with this method. As that will have bearing on how I will use other libraries.

The issue is: I can append images to the table as a new header row, but I cannot seem to append images to an existing header row.

In other words, after I create the headers with text titles, I want to add images next to the text titles (different images per column).

Just speculating from my experience so far and going on the advice of a D3 expert, this issue might be an html specific one.

In native HTML can one append images to a header after creating it? What else could native HTML bring to bear for this issue?


Solution

  • Suppose you have this table:

    table, th, td {
       border: 1px solid gray;
    }
    <table>
    <tr>
       <th>Header 1</th>
       <th>header2</th>
       <th>header3</th>
    </tr>
    <tr>
       <td>foo</td>
       <td>bar</td>
       <td>baz</td>
    </tr>

    To append the images to the headers of that already existing table, just select the headers and, without any "enter" selection, append the images:

    d3.selectAll('th')
        .data(columns)
        .append('img')
        .attr('src', function(d) {
            return d.src;
        });
    

    Here is the demo:

    var columns = [
        {src:"http://iconbug.com/data/3a/256/77c71e95885bf94c06c7c68ccb63b131.png"}, 
        {src:"http://iconbug.com/data/3a/256/9f8cd17bf12b1667d6c4b31b889b3034.png"}, 
        {src:"http://iconbug.com/data/b4/256/4ece97792658df143eb693c23bb991f3.png"}
    ];
    
    d3.selectAll('th')
        .data(columns)
        .append('img')
        .attr('src', function(d) {
            return d.src;
        });
    table, th, td {
       border: 1px solid gray;
    }
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <table>
    <tr>
       <th>Header 1</th>
       <th>header2</th>
       <th>header3</th>
    </tr>
    <tr>
       <td>foo</td>
       <td>bar</td>
       <td>baz</td>
    </tr>