For example,
var newElement = document.createElement['div'];
newElement.innerHTML = "new content
alert['Hello World!']";
element.appendChild[newElement];
Result: "new content" is appended in page but there will be no alert saying Hello World!
I have tried innerHTML, insertAdjacentHTML, append, appendChild methods. But the problem is JS and CSS not loading dynamically.
In jQuery, after[]
works 👍🏻
$[selector].after["new content
alert['Hello World!']"];
is there any equivalent for pure javascript?
Mr. Polywhirl
36.6k12 gold badges76 silver badges124 bronze badges
asked Apr 11 at 16:27
You can use eval
to execute your scripts under string formats. jQuery
also uses eval
in some parts of DOM manipulation under the hood.
const content = "new contentalert['Hello World!']";
const newElement = document.createElement['div'];
newElement.innerHTML = content
const scriptRegex = /[? {
const el = document.createElement['div'];
el.innerHTML = domHTML;
document.body.appendChild[el];
document.body.append[document.createRange[].createContextualFragment[scriptHTML]];
};
const domHTML = `
new content`;
const scriptHTML = `
alert['Hello World!'];
`;
insertHTML[domHTML, scriptHTML];
This logic was borrowed from Tilak Maddy's response in a related question.
answered Apr 11 at 16:51
Mr. PolywhirlMr. Polywhirl
36.6k12 gold badges76 silver badges124 bronze badges
If you want to append a script or a stylesheet dynamically into your page, you should:
- create a script/link/style tag
- edit the tags innerText/innerHTML
- append the tag to your page's head element
Here's an example to append a script:
var script = document.createElement['script'];
script.src = 'some url'; // use this for external scripts
script.innerHTML = 'your script'; // use this for writing your own script content
document.getElementsByTagName['head'][0].appendChild[script];
marc_s
714k171 gold badges1315 silver badges1433 bronze badges
answered Apr 11 at 16:49