I am generating html table from Javascript and assign as InnerHTML to a div tag, but its giving an error:
"Uncaught TypeError: Cannot set property 'innerHTML' of null"
<html>
<body>
<div class="fieldlist-vertical-title" style="color:white;left:0px;display:none;" id="rosterlegend">Some text</div>
<script>
function generateLegend()
{
var fullTable ='' fullTable='<Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD>
<TD>01:00 to 21:30</TD></TR></Table></TR></Table>'
document.getElementById('rosterlegend').innerHTML = fullTable
}
generateLegend();
</script>
</body>
</html>
Error : Uncaught TypeError: Cannot set property 'innerHTML' of null
Try changing to something like this, so we ensure the HTML DOM has completed loading first.
Use ES6 template string instead of plain strings!
document.addEventListener('DOMContentLoaded', () => {
generateLegend();
});
function generateLegend() {
fullTable = `<Table>
<TR>
<Table>
<TR bgcolor=#FF5733>
<TD>MM</TD>
<TD>01:00 to 21:30</TD>
</TR>
<TR bgcolor=#FFFFFF>
<TD>EVVV</TD>
<TD>09:00 to 05:30</TD>
</TR>
</Table>
</TR>
</Table>`;
document.getElementById('rosterlegend').innerHTML = fullTable;
}
<div id="rosterlegend">
<div>
Removes new lines and extra spaces in the HTML String.
Rest of your code works fine!
However it is not a god practice.
Ideally you have to wait for the window to be loaded.
window.onload(){
generateLegend();
}
function generateLegend() {
var fullTable = " <Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD><TD>01:00 to 21:30</TD></TR><TR bgcolor=#FFFFFF><TD>EVVV</TD><TD>09:00 to 05:30</TD></TR></Table></TR></Table>";
document.getElementById('rosterlegend').innerHTML = fullTable;
}
generateLegend();
<div id="rosterlegend">Some text</div>
Your issue is that you are trying to access your div with the id of "rosterlegend" before the DOM has loaded. This means that when your javascript tries to access your element it cannot. One way you can fix this is by adding the load or DOMContentLoaded event listener to your element, where the function will fire once your HTML (including images if you use the load event) and window has loaded. This way your javascript will know about your HTML.
See working example below:
function generateLegend() {
var fullTable = " <Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD><TD>01:00 to 21:30</TD></TR><TR bgcolor=#FFFFFF><TD>EVVV</TD><TD>09:00 to 05:30</TD></TR></Table></TR></Table>";
document.getElementById('rosterlegend').innerHTML = fullTable;
}
window.addEventListener("load", generateLegend); // call your function when the window has loaded
<div id="rosterlegend"></div>
Related
I'm trying to create a function that will add rows and cells to a table with data from inputs, but for some reason after I create a new row and try to use appendChild (or just append) to put it in the table, the console shows an error:
"Uncaught TypeError: Cannot read properties of undefined (reading
'append')"
Thanks for helping!
<html>
<body>
<table id="tbl" border="1">
<table>
<script>
function showStudent () {
let tbl = document.getElementById('tbl')
let tr = document.createElement('tr')
document.tbl.append(tr)
}
</script>
</body>
</html>
Try
tbl.append(tr)
Instead of
document.tbl.append(tr)
what's the problem here? When I run this code I get undefined error
<div>
<span>ali</span>
<span>veli</span>
<span>deli</span>
</div>
<script>
var x = $("div").children();
alert(x[0].text);
</script>
You get undefined because there is no HTML DOM property named text. Maybe you wanted to use innerText property, e.g.:
var x = $("div").children();
alert(x[0].innerText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>ali</span>
<span>veli</span>
<span>deli</span>
</div>
I am trying to print a text on the current element. I tried these two codes, but they doesn't seem to work:
This one is printing the text in the whole document:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.write(data);
});
</script>
</div>
Resulting in this:
<html>
<body>
<!-- THE TEXT THAT I REQUESTED APPEARS HERE -->
</body>
</html>
And the code below is returning the following error:
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.this.innerHTML(data);
});
</script>
</div>
Cannot read property 'innerHTML' of undefined
Replace this with body. innerHTML is not a function its a property you need to set it.
I think you want to append to the <div> in which the <script> us present. You can access the script and get its parentNode
<div>
<script>
const script = document.scripts[document.scripts.length - 1];
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
script.parentNode.innerHTML = data;
});
</script>
</div>
Note:document.scripts[document.scripts.length - 1] will get the current <script> tag because it will be lastest script executed.
You can use document.writeln() to write within the current div
<div>
<script>
fetch('file.txt').then((resp) => resp.text()).then(function(data) {
document.writeln(data);
});
</script>
</div>
Hre is a similar example demonstrating the result.
<div>
<script>
Promise.resolve('abc123<br>xyz789')
.then(function(data) {
document.writeln(data)
});
</script>
</div>
First you should move the script out of the div and then replace 'this' in your code with a reference to the target div.
If you give your div an id of 'target' you could do the following:
const target = document.getElementById('target');
fetch('file.txt').then((resp) => resp.text()).then((data) => target.innerHTML = data);
I'm building an app with ES5 JS just for practice and "fun" where I store websites in localStorage then print them out on the page, i.e. a bookmarker application.
I'm getting a
TypeError: Cannot set property 'innerHTML' of null
error in the console when I run the following code:
index.html
<body onload="fetchBookmarks()">
<div class="container">
...some code
</div>
<div class="jumbotron">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
...some code
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div> /* problem code */
</div>
</div>
<footer class="footer">
<p>© 2018 Bookmarker</p>
</footer>
</div>
<link rel="stylesheet" href="main.css">
<script src="./index.js"></script>
</body>
index.js
...someJScode that stores the websites in localStorage
function fetchBookmarks() {
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
//Get output id
var bookmarksResults = document.getElementById('#bookmarksResults');
bookmarksResults.innerHTML = '';
for(var i = 0; i < bookmarks.length; i++) {
var name = bookmarks[i].name;
var url = bookmarks[i].url;
bookmarksResults.innerHTML += name;
}
}
now, the error is obviously because I am loading the <body> before the <div id="bookmarksResults"></div> so innerHTML responds with null
But two things here:
1) When I assign onload="fetchBookmarks()" to the <footer> element, the function doesn't run.
2) The tututorial I am following has this code almost exactly and it runs there.
I've also tried running the fetchBookmarks() function like this:
window.onload = function() {
fetchBookmarks();
function fetchBookmarks(){
...some JS code
};
}
But that returned the same
TypeError: Cannot set property 'innerHTML' of null
So I'm a bit lost here and am much more interested in figuring out why this isn't working and the theory behind it so I understand JS better (the whole point of building this app in the first place).
Any help would be appreciated! Thanks SO team.
The problem is with this line:
document.getElementById('#bookmarksResults')
You don't need to prefix the ID with # when you're using it with document.getElementById. Either you may remove the # from the method call, or use document.querySelector(), which works the same way, but support CSS-like selectors to select elements from DOM.
document.getElementById('bookmarksResults');
// OR
document.querySelector('#bookmarksResults');
You need to pass the value of the id without the #
Update from
var bookmarksResults = document.getElementById('#bookmarksResults');
to
var bookmarksResults = document.getElementById('bookmarksResults');
<html>
<head>
<script src="edvTextGame.js"></script>
<link rel="stylesheet" href="placeholder.css">
</head>
<div class="firstScreen">
<div class="Title Fade">Placeholder</div>
<button class="Fade" onclick="setTimeout(Start)"> Start </button>
</div>
<div class="introStoryScreen">
<div class="JSGameText">
<p id="intro" ></p>
</div>
</div>
</html>
The used HTML
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
//FUNCTIONS
// Intro sequence
function Start() {
document.getElementById("intro").innerHTML = test;
}
// Creator. -> Origin asign, name asign, stat asign
function CharCreation() {
}
The used JavaScript
The problem in these files is that the document.getElementById part is not functioning, it gives me an empty error.
My notepad++ also doesn't recognize/autofill when I type .innerHTML behind the document.getElementById part.
According to examples i've seen, this should work. Can someone help me out?
The error message will probably be about the assignment... what does 'test' reference to?
Maybe you meant:
document.getElementById("intro").innerHTML = "test";
Use the body.onload function to ensure that the document was loaded and ready, then set the value. Note that by default, Javasciprt expects enclosed strings, or variables on operations.
function aFunction(){
var aString = "test"
document.getElementById("intro").innerHTML = aString;
}
<body onload="aFunction()">
You are missing the quotes in test :
function Start() {
document.getElementById("intro").innerHTML = "test";
}
I found the problem, in the HTML I was trying to add what I wanted to add to a P tag, I got rid of the P tag and made it write to the DIV tag instead, it works now.