best way to write html into an existing page javascript
<p>this probably isnt the "best way" but it is a way that works.</p>
<p>say you want to add some elements to a page with javascript this is a method to do it. </p>
<p>Add an element, before including the script, just to be sure that you have your own element to write to, makes it a bit easier. </p>
<h3>Error: Uncaught TypeError: kx.innerHTML is not a function</h3>
<p>not sure why im getting this erro, the id is correct. </p>
<p><img src="https://i.imgur.com/kz3Q2AZ.png" /></p>
<p>So this is caused as the element is not yet written to the dom, so it does not exist to be updated yet. </p>
<p>Need to add an onload to wait for the element to exist before updating it. </p>
<pre class="lang-js s-code-block"><code>window.onload = function() {</code><br /><code> / like a document ready in jquery, but no jquery.. add the code here instead /</code><br /><code>}</code></pre>
<p>Still getting the same error, i think i need to combine the line.</p>
<p>Rather than this:</p>
<p><code>window.onload = function() {</code><br /><code> var myelementtest = document.getElementById("myelementtest");</code><br /><code> myelementtest.innerHTML('<p>dynamic kruxor</p>');</code><br /><code>}</code></p>
<p>do this</p>
<p><code>window.onload = function() {</code><br /><code> document.getElementById("myelementtest").innerHTML('<p>dynamic kruxor</p>');</code><br /><code>}</code></p>
<p>Actually that is wrong again!</p>
<p>dont use the brackets for innerHTML it needs the =</p>
<p>This should work now.</p>
<p>it may not need the onload function either. </p>
<p><code>document.getElementById("myelementtest").innerHTML = '<p>dynamic kruxor</p>';</code></p>
<p class="alert alert-info"><strong>Note about innerHTML</strong>: <br />make sure you use .innerHTML = value rather than .innerHTML("value")</p>
HTML
<div id="my_element_test"> </div>Javascript
/*
// this one is wrong
window.onload = function() {
document.getElementById("my_element_test").innerHTML('<p>dynamic kruxor</p>');
}
*/
/* Just to be sure it is ready to write, add the window.onload function as well */
window.onload = function() {
document.getElementById("my_element_test").innerHTML = '<p>dynamic kruxor</p>';
}
<div id="myelementtest"> </div>