I've only just started playing with Pyscript, and I'm trying to use it to dynamically update some HTML markup on my page at run-time. (I rarely program in Javascript, so there are plenty of gaps in my knowledge when it comes to programming the DOM, etc., etc).
If I start with this markup:
<div id="charts">This is a <b>Test</b>.</div>
<py-repl>
</py-repl>
I can type these next three lines of code into the py-repl prompt, using the innerHTML attribute to adjust the markup within the div tag, updating the page on-the-fly, like so:
from js import document
c = document.getElementById('charts')
c.innerHTML = "This is <i>another</i> test."
Sure enough, the new innerHTML markup replaces the older markup, the page updates, and all is well in the world (with the word "another" appearing italicised). This is exactly what I was expecting to happen.
However, when I use the same code within a py-script tag, like so:
<div id="charts">This is a <b>Test</b>.</div>
<py-script>
from js import document
c = document.getElementById('charts')
c.innerHTML = "This is <i>another</i> test."
</py-script>
The markup is replaced with the string "This is another test.". The HTML markup is stripped away, as if I'd used innerTEXT instead of innerHTML. The page does update but, with the italics tag missing, I'm not seeing rendered markup, only the textual content.
What am I doing wrong?
Any help/pointers greatly appreciated.
CodePudding user response:
PyScript removes HTML markup from strings. To embed HTML, one option is to build the DOM elements like this:
<py-script>
from js import document
c = document.getElementById('charts')
c.innerHTML = ""
e = document.createTextNode("This is ")
c.appendChild(e)
e = document.createElement("i")
e.innerHTML = "another"
c.appendChild(e)
e = document.createTextNode(" test.")
c.appendChild(e)
</py-script>