Tuesday, 5 March 2019

Access an element by id inside Jupyter notebook _repr_javascript_ method

I cannot retrieve a newly added html object using its id while inside the Jupyter output cell. How can I do it?

EDIT: I have been able to replicate the same behavior in a notebook hosted on Azure:

https://notebooks.azure.com/rickteachey/projects/sandbox/html/js_repr_id_access.ipynb

NOTE: to run this notebook, click Clone at the top right and run it in your own Azure project/notebook.

The javacript first adds a new html button using the Jupyter API (ie, element.html(); in context, element refers to the Jupyter output cell <div>).

Then the code attempts to access the button using document.getElementById():

class C:
    def _repr_javascript_(self):
        return f'''
        element.html(`<button id="clearBtn">Clear</button>`)
        var x = document.getElementById("clearBtn")
        alert(x)
        '''

C()

EXPECTED BEHAVIOR: The alert should show a stringified version of the clearBtn html button object.

ACTUAL BEHAVIOR: The alert shows a null object, which means the script fails to grab the clearBtn - even though I can see it in the DOM when I look at the source.

It's possible I'm using the API incorrectly. If so, how am I supposed to do this?

Another weird issue: when I look at the same notebook on nbviewer, the alert pops up the clearBtn html object as expected. It does NOT behave this way on my local machine(s), or on Azure. Should I report this as a bug?

https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/dwfmnozfn42w0ck/access_by_id_SO_question.ipynb



from Access an element by id inside Jupyter notebook _repr_javascript_ method

No comments:

Post a Comment