I need to trigger a script inside of another element, when that element becomes a target of certain function.
<div id="myParent">
<script>
//listens for myFunction(myParent) {
Alert("myParent was target of myFunction")
}
</script>
</div>
function myFunction(target){
//do something with the target
}
So the expected/desired result is
myFunction("myParent") //"myParent was target of myFunction"
So I know how to add event listeners but none of them really do what I need them to, or at least I wasn't able to find a way to customize them to suit my needs. On the other hand I managed to call the Script by targeting the parenent element, finding the script within it and triggering it using eval(), however I am not a fan of this method as I would have to check every element that gets passed in myFunction() to see if has a condition which triggers its script. Like so:
<div id="myElement_1">
<p>true</p>
<script>
//listens for myFunction(myParent) {
"Alert("Hello")"
}
</script>
</div>
<div id="myElement_2">
<p>False</p>
<script>
//listens for myFunction(myParent) {
"Alert("World!")"
}
</script>
</div>
function myFunction(target){
let checkCondition = target.getElementsByTagName("p")[0].innerText
if(checkCondition === "true"){
let trigger = target.getElementsByTagName("script")[0]
eval(trigger)
}
}
myFunction(myElement_1) // "Hello"
myFunction(myElement_2) //
Im afraid that using this solution would eventually clog up my code with thousands of checks within my functions, as each potential target has quite unique trigger conditions. So it makes more sense for the to listen for it's own triggers, I just am not able to figure out how to do that.
You can't do that. Once a tag <script> appears in html (except xss innerHTML), it will be forced to run even if you delete the tag.
You can save data into the html tag and call it out by:
<div id="app" data-text="Hello App" />
console.log(document.querySelector("#app").getAttribute("data-text"))
Or if you really need to run a script, you can lazyly download it with fetch.