Access an element by id inside Jupyter notebook _repr_javascript_ method

327 views
Skip to first unread message

Ricky Teachey

unread,
Mar 3, 2019, 8:26:45 AM3/3/19
to Project Jupyter
Hi all, Jason Grout suggested I cross post this question here from stackoverflow:

https://stackoverflow.com/questions/54963230/access-an-element-by-id-inside-jupyter-notebook-repr-javascript-method

How can I grab an element using its id while inside the Jupyter output cell? I have added the element using the Jupyter API (ie, element.html).

I have gotten this far:

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

C()
}
```

The alert shows a null object. So 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. How am I supposed to do this?

Another weird issue: when I look at the same notebook on nbviewer, the alert pops up the stringified version of the clearBtn HTML object as expected. It does NOT behave this way on my local machine(s).

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

Ricky Teachey

unread,
Mar 4, 2019, 9:38:37 AM3/4/19
to Project Jupyter
UPDATE: I have been able to replicate the behavior on a Azure-hosted notebook.

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.

So the unexpected behavior occurs in Azure, and locally on two machines I have tried using the latest Anaconda (both on a Windows machine, and on a Chromebook running a Linux (Beta) container). However it does not replicate on nbviewer:

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

Ricky Teachey

unread,
Mar 4, 2019, 9:42:09 AM3/4/19
to Project Jupyter
Sorry: here is the Azure notebook.

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

Should I open an issue? This is starting to smell like a bug but I'm not sure.

Ricky Teachey

unread,
Mar 4, 2019, 1:45:46 PM3/4/19
to Project Jupyter
Success!

It turns out that the `element` is some kind of jquery object, and I should have been doing this:

element.find("#clearBtn")

...instead of this:

$("#clearBtn")

...or this:

document.getElementById("clearBtn")

As a novice, this wasn't clear to me at all reading the docs.

Sorry to fill up all your inboxes with my ignorance.

- Rick

Reply all
Reply to author
Forward
0 new messages