d3.js Playing with Selections

One should have a good understanding of selections, it is worth playing with a sandbox and explore the various options you have. I adopted the tutorial from Mike here.

Lets assume we have a simple HTML table:

<!DOCTYPE html>
<html>
    <head>
        <title>Selections</title>
        <script type="text/javascript" src="lib/d3.v2.min.js"></script>
    </head>
    <body>
        <table>
            <thead>
                <tr><td>  A</td><td>  B</td><td>  C</td><td>  D</td></tr>
            </thead>
            <tbody>
                <tr><td>  0</td><td>  1</td><td>  2</td><td>  3</td></tr>
                <tr><td>  4</td><td>  5</td><td>  6</td><td>  7</td></tr>
                <tr><td>  8</td><td>  9</td><td> 10</td><td> 11</td></tr>
                <tr><td> 12</td><td> 13</td><td> 14</td><td> 15</td></tr>
            </tbody>
        </table>
        <script type="text/javascript">
           //nothing yet
        </script>
    </body>
</html>

HTML table

Now lets select various combinations of the table structure and its cells by inserting a select statement in the <script> section and replace the text with “0”

Complete table

d3.selectAll("table").text("0");

All cells

d3.selectAll("td").text("0");

All cells of the body

d3.selectAll("tbody td").text("0");

One specific row using an ID

First row

<tr id="row1" ><td>  0</td><td>  1</td><td>  2</td><td>  3</td></tr>
d3.selectAll("#row1 td").text("0");

Leave a comment