Reputation: 37
In the code below, I have a defined script with an ID so I may access it from the DOM. As you can see, I request the defined script in the DOM during the definition of the script. How does this not recursively call its self when requesting the innerhtml call?
My guess is that the DOM parses the defined script and placed the the ID into the DOM. During execution in the browser the JS gets the element by the ID and loads the HTML from the script. I feel like a recursive call would be constructed because during the execution on the browser side, we need to get the HTML in the innerHTML method, which will execute the JS script again?
Question: Is my assumption correct or am I missing something about the DOM, if so what is it that I do not know?
<script id="myScript">
var x = 1;
var y = 2;
if (x != y) {
var html_code = document.getElementById("myScript").innerHTML;
//More JavaScript Below here
console.log(html_code);
}
</script>
Upvotes: 2
Views: 49
Reputation: 33726
That code returns the current HTML of an element.
Who executes the rendering/parsing/compiling process is the browser itself or whatever middleware who parses/renders/compiles the HTML code, scripts, Etc.
<script id="myScript">
var x = 1;
var y = 2;
if (x != y) {
var html_code = document.getElementById("myScript").innerHTML;
console.log(html_code)
}
</script>
The Element property
innerHTML
property is used to get or set a string representing serialized HTML describing the element's descendants.
So, that attribute won't execute any compiling process or script.
Upvotes: 0
Reputation: 3956
When you store the element's innerHTML
into the variable html_code
, the text that is inside the <script>
tag -- that is, the actual script itself -- is returned, and it is displayed as text in the console. But just displaying that code won't actually execute it.
Now, if you were to use eval()
on your html_code
variable, that would execute the code. See the below example:
<script id="myScript">
var x = 1;
var y = 2;
if (x != y) {
var html_code = document.getElementById("myScript2").innerHTML;
//More JavaScript Below here
eval(html_code);
}
</script>
<script id="myScript2">
alert("test");
</script>
Upvotes: 1
Reputation: 2076
Your assumption, that a request to .innerHTML
will rerun the javascript is wrong. It will just return the text of the element.
Upvotes: 2