py_d3 icon indicating copy to clipboard operation
py_d3 copied to clipboard

How to wrangle raw selections? Getting a DOMException

Open johncarmack1984 opened this issue 6 years ago • 1 comments

Hi there! :)

I've got code that works in a browser on its own, but doesn't transfer to py_d3, and it doesn't seem to fall under the stuff already in the readme or other issues.

Running this code:

%%d3

<style>
.table {
    width: 70%;
}

.table td, th {
    padding: 5px;
}
.table-header {
    background-color: #00AFEF;
    font-weight: bold;
}

.table-row-odd {
    background-color: #f0f8ff;
    color: blue;
}

.table-row-even {
    background-color: #d3d3d3;
}
</style>
<table class="table">
    <thead>
    <tr>
        <th>Time</th>
        <th>Type</th>
        <th>Amount</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>10:22</td>
        <td>Purchase</td>
        <td>$10.00</td>
    </tr>
    <tr>
        <td>12:12</td>
        <td>Purchase</td>
        <td>$12.50</td>
    </tr>
    <tr>
        <td>14:11</td>
        <td>Expense</td>
        <td>$9.70</td>
    </tr>
    </tbody>
</table>

<script type="text/javascript">
    var trSelection = d3.selectAll("tr"); // <-- A

    var headerElement = trSelection.nodes()[0]; // <-- B
    console.log("headerElement is an instance of DOM Element: " 
        + (headerElement instanceof Element));

    d3.select(headerElement).attr("class", "table-header"); // <-- C
    console.log("d3.select(headerElement) is an instanceof of d3.selection: " 
        + (d3.select(headerElement) instanceof d3.selection));

    var rows = trSelection.nodes();
    d3.select(rows[1]).attr("class", "table-row-odd"); // <-- D
    d3.select(rows[2]).attr("class", "table-row-even"); // <-- E
    d3.select(rows[3]).attr("class", "table-row-odd"); // <-- F
</script>

In-browser yields: screen shot 2018-04-12 at 12 25 42 pm console: screen shot 2018-04-12 at 12 25 56 pm

In jupyter/py_d3 yields: screen shot 2018-04-12 at 12 27 03 pm

Javascript error adding output!
SyntaxError: Failed to execute 'querySelector' on 'Element': '[object HTMLTableRowElement]' is not a valid selector.
See your browser Javascript console for more details.

console: screen shot 2018-04-12 at 12 28 50 pm

I'm just learning D3 using some tutorials, and I don't know much about DOM manipulation, is there something in jupyter that makes this illegal? I'm going to move on to the next tutorial for now, but wanted to pass this along in case this is a bug rather than a feature. :)

johncarmack1984 avatar Apr 12 '18 19:04 johncarmack1984

Looks to me like Jupyter automatically applies its own styling to table elements. That is colliding with your D3 selection somehow, resulting in this unexpected result.

I'll have to take a look to see what the problem is. Thanks for reporting!

ResidentMario avatar Apr 12 '18 19:04 ResidentMario