1 | initial version |
There are different ways to insert HTML code dynamically and run it, depending on the programming language and framework used. Here is a general approach:
innerHTML
property of an element to set its content to the HTML code.Here is a sample code in JavaScript that inserts HTML code dynamically and runs its scripts:
let htmlCode = "<div><h1>Hello, world!</h1><script>alert('Welcome!');</script></div>";
let element = document.getElementById("my-element");
element.innerHTML = htmlCode;
let newScript = document.createElement("script");
newScript.innerHTML = "console.log('Script executed.')";
element.appendChild(newScript);
This code inserts a <div>
element containing an <h1>
tag and a script that shows an alert message. Then, it creates a script element that logs a message to the console and adds it to the same <div>
element. When the code runs, the HTML code and scripts are inserted and executed dynamically.