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');
Related
I'm trying to make it so only some specific boxes get padding on the left and right but the code doesn't pass the "getElementByClassName"-part. I get the alert "Test1" but not "Test2" so the problem is somewhere on that line I think.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" >
var numProducts = $('.product').length;
for(var i = 1;i<numProducts;i++){
var x = (i+1)/3;
if(x%1=0){
alert("test1");
var box = document.getElementByClassName('product')[i-1];
alert("test2");
box.style.paddingRight ="30px";
box.style.paddingLeft="30px";
}
}
</script>
I get the right values from numProducts, i and x so I don't think they are the problem. What am I supposed to do? Thanks
What you expected should be document.getElementsByClassName rather than document.getElementByClassName.
The following is my version of your script. I would recommend that you actually use jQuery, as you have clearly loaded it already. And using jQuery means that something like document.quersSelectorAll() is not needed anymore.
$('.product').each(function(i){
i%3==2 && $(this).addClass("padded")
})
.padded {padding-right:30px;
padding-left:30px;}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="product">a</div>
<div class="product">b</div>
<div class="product">c</div>
<div class="product">d</div>
<div class="product">e</div>
<div class="product">f</div>
<div class="product">g</div>
<div class="product">h</div>
<div class="product">i</div>
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>
<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.
I created a logger window for my Django website - basically just grabs lines from a .txt log file that my views.py python logger creates and displays them in a popup window. The code I created to do this grabs lines from the log file every second and uses javascript to write them to a <span> element. I want to be able to color code the messages based on the message level (ERROR = red, WARNING = yellow, etc) but can't seem to figure it out.
EDIT
I was able to color the first WARNING message but am not sure how to get it to color all of them.
The html/javascript code to create the log window looks like this:
<body>
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-heading text-center">
<h4 class="text-center">Log Messages</h4>
</div>
<div class="panel-body">
<div class="content" id="logtext">
<font face="courier">
<span id="show" class='value'></span>
</font>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
function saveLogs(data){
sessionStorage.setItem("logs",data.message);
}
$(document).ready(
function() {
setInterval(function() {
Dajaxice.InterfaceApp.getLogs(saveLogs);
var logs = sessionStorage.getItem("logs");
document.querySelector('.content .value').innerText = logs;
$("div:contains('WARNING')").each(function () {
$(this).html($(this).html().replace("WARNING", "<span class='red'>WARNING</span>"));
});
}, 1000);
});
</script>
</div>
</body>
The Dajaxice calls this python function:
def getLogs(request):
fname = log_path
with open(fname,"r") as f:
lines = f.readlines()
lines = lines[-1000:]
return json.dumps({'message':lines})
The log window currently looks like this:
and I want to be able to color code the messages based on the level. I've tried a couple things (this, and this) but no luck.
Looks the log messages have a fix and simple format, a string replace on the whole log could be used, without the JQuery part:
document.querySelector('.content .value').innerHTML = colorize(logs);
function colorize(logs) {
return logs.replace("(WARNING)", "(<span class='red'>WARNING</span>)");
}
I am trying to build a template builder using http://ejohn.org/blog/javascript-micro-templating
My html has this script tag
<script type="text/html" id="item_tmpl">
<div>
<div class="grid_1 alpha right">
</div>
<div class="grid_6 omega contents">
<p><b><%=AdTitle%>:</b> <%=AdTitle%></p>
</div>
</div>
</script>
<script src="${URLUtils.staticURL('/js/shoptheAd.js')}"type="text/javascript"></script>
The Script contains the following code
(function(app){
if (app) {
var cache = {};
this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn( data ) : fn;
};
var sitecoresuggestions = {
"suggestions": [
{
"AdTitle": "CheckAd",
"AdDescription": "",
"AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/emma-watson-3.ashx",
"Count": 2,
"Hit": 0
},
{
"AdTitle": "CheckAd",
"AdDescription": "",
"AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/kate2.ashx",
"Count": 2,
"Hit": 0
}
]
} ;
var show_user = tmpl("item_tmpl"), html = "";
for ( var i = 0; i < sitecoresuggestions.suggestions.length; i++ ) {
html += show_user( sitecoresuggestions.suggestions[i] );
}
console.log(html);
} else {
// namespace has not been defined yet
alert("app namespace is not loaded yet!");
}
})(app);
When the show_user = tmpl("item_tmpl") is executed
i get the error TypeError: document.getElementById(...) is null
on debugging i have figured out that due to some reason
<script type="text/html" id="item_tmpl">
<div>
<div class="grid_1 alpha right">
</div>
<div class="grid_6 omega contents">
<p><b><%=AdTitle%>:</b> <%=AdTitle%></p>
</div>
</div>
</script>
does not get loaded in the browser any ideas why it is not getting loaded even though it is included inside the head tag or any other pointers for the cause of the error
Per the post:
Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - >the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and >by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into >your page. I like to use this technique for quick-and-dirty cases where I just need a little >template or two on the page and want something light and fast.
So the page doesn't actually render the HTML, and I would assume you would only have reference to it in the page so that you can extract and apply to other objects or items. And as the blogger states you would use it like:
var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);