My regular javascript code seems to be outputting stuff to the page either incorrectly or in the wrong order, which is weird because the code is very simple (maybe 20 lines tops). My code is below. Note:
pttr_data.lengthwill return 150clean_array.lengthwill return 4.outputis a div object, i.e. var output = document.getElementById(“results”);
I want my code to output like this:
<div>matcha matchb matchc matchn </div>
But instead it returns:
<div/>matcha matchb matchc match
Here is my code, in which I placed random characters to figure out where stuff is going (you’ll see the ;;;, |||, [[[, }}} in there surrounding the divs):
var len = pttr_data.length;
for (var i = 0; i < len; i++) {
var clean_array = pttr_data[i].match(RegExp(rexp.value, flags.value));
output.innerHTML += ";;;<div>|||";
var lengthy = clean_array.length;
for (var j = 1; j < lengthy; j++) {
if( clean_array[j] ) { output.innerHTML += clean_array[j] + ' '; }
else { output.innerHTML += 'NULL '; }
}
out.innerHTML += "[[[</div>}}}\n";
}
This code returns:
;;;<div>|||</div>matcha matchb matchc [[[}}}
Can someone explain why this occurs? Do javascript for loops operate independently (and thus finish at varying speeds), even if they are nested? This makes no sense though, why would someone design a scripting language like that?
How could my code output <div/>blah instead of <div>blah</div> ?
Thanks
The
.innerHTMLproperty is a bit more complicated than just a string you can append to. If you append"<div>"to it (or";;;<div>|||"in your example) the browser doesn’t wait around to see if you’ll eventually supply a closing</div>tag, it just creates a div immediately. Then you append more text:"matcha", "matchb", etc. And finally you append a closing</div>that the browser ignores because, again, it wasn’t waiting for it, but it keeps the"[[[}}}".Instead of appending to
.innerHTMLas you go, append to a string variable and then set.innerHTMLequal to that string at the end.If you want to append all elements of
clean_arrayseparated by spaces you don’t even need theforloop, you can just use.join():But to keep your nested for loop: