best way to write html into an existing page javascript
this probably isnt the "best way" but it is a way that works.
say you want to add some elements to a page with javascript this is a method to do it.
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.
Error: Uncaught TypeError: kx.innerHTML is not a function
not sure why im getting this erro, the id is correct.
So this is caused as the element is not yet written to the dom, so it does not exist to be updated yet.
Need to add an onload to wait for the element to exist before updating it.
window.onload = function() {
/* like a document ready in jquery, but no jquery.. add the code here instead */
}
Still getting the same error, i think i need to combine the line.
Rather than this:
window.onload = function() {
var my_element_test = document.getElementById("my_element_test");
my_element_test.innerHTML('<p>dynamic kruxor</p>');
}
do this
window.onload = function() {
document.getElementById("my_element_test").innerHTML('<p>dynamic kruxor</p>');
}
Actually that is wrong again!
dont use the brackets for innerHTML it needs the =
This should work now.
it may not need the onload function either.
document.getElementById("my_element_test").innerHTML = '<p>dynamic kruxor</p>';
Note about innerHTML:
make sure you use .innerHTML = value rather than .innerHTML("value")
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>';
}