2

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

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.