In Jupyter notebook we may use some magic functions shortcuts like so:
%%javascript
element.text('Hi')
This outputs in the current cell as expected. (If I'm not mistaken element here stands for current cell in DOM of jupyter notebook).
'Hi'
Question: Is there a way to do the same with %%html?
My naive attempt doesn't work.
%%html
<script>element.text('Hi');</script>
Notice that such construct works just fine.
%%html
<script>alert('Hi');</script>
I'm not that good with jQuery and notebook DOM structure, so some explanation will be welcome. I read a few similar questions, like 16852885 but fail to find the relevant analog.
1 Answer 1
As far as I know, the element variable is not directly available in an %%html cell. To have access to the element variable, you first need to create it. It should be the parent of the <script> tag in the %%html cell. An easy way to get the <script> tag is to give it an ID.
If you don't need jquery, you can do the following:
%%html
<script id="unique">
var element = document.getElementById('unique').parentElement;
element.innerHTML = "Hi";
</script>
If you want to use jquery, you should load it first:
%%html
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script id="unique2">
var element = $('#unique2').parent();
element.text("Hi (jquery)")
</script>