I have this simple javascript snippet
function foo() {
bar();
}
function bar() {
var tags = document.getElementsByTagName('example');
for (var i = 0; i < tags.length; i++) {
console.log(tags.length);
tags[i].innerHTML = '<example2>Inserted</example2>';
}
}
foo();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>
<example></example>
The thing I don't get is that when I change the inserted innerHTML to be Inserted it doesn't exit the loop as it keeps "updating" the variable tag (I added the 2 in the snippet to avoid it if you run it);
As a side note, if I use the lodash forEach it does what I expected to do with the for loop, just runs the loop code once.
function foo() {
bar();
}
function bar() {
var tags = document.getElementsByTagName('example');
_.forEach(tags, function(value) {
console.log(tags.length);
value.innerHTML = '<example>Inserted</example>';
});
}
foo();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>
<example></example>
I can't understand why the loop keeps udpdating the variable with the nested tags.
Thanks