innerHTML not displaying - javascript

Apologies for asking such a trivial question (just learning how JS works) but I am getting a headache for next to nothing. Maybe I am tired and just don't see what I am doing but why is the below not working - i.e. value of totalBits to print in the body of the 'print' div? If I alert() it shows the value but not using the innerHTML.
<html>
<head>
<title></title>
<script type="text/javascript">
function answer(sentence){
var bitsOfString = sentence.split(" ");
var numOfBits = bitsOfString.length;
return numOfBits;
}
var sentence = prompt("OK, say something!")
var totalBits = answer(sentence);
var div = document.getElementById("print");
div.innerHTML = totalBits;
</script>
</head>
<body>
<div id="print"></div>
</body>
</html>

Because you are calling it before the element is rendered to the page. Move the script after the element is loaded or you can call your code window onload/document ready.
<html>
<head>
<title></title>
</head>
<body>
<div id="print"></div>
<script type="text/javascript">
function answer(sentence) {
var bitsOfString = sentence.split(" ");
var numOfBits = bitsOfString.length;
return numOfBits;
}
var sentence = prompt("OK, say something!")
var totalBits = answer(sentence);
var div = document.getElementById("print");
div.innerHTML = totalBits;
</script>
</body>
</html>

Have a look at your error console. You should get div is null as an error, because the element hasn't been parsed yet.
You need to put your script block after your div element or defer the execution of the script.

Most likely your JavaScritpt executes before the DOM is ready.
In other words, wrap your javascript where you manipulate the div in document.onload function or if you're happy to use jQuery: $(function(){});
You can see it working here: http://jsfiddle.net/c8tyg/
P.S.
I'm not the fan of moving the <script> blocks around because IMHO JavaScript should work regardless how you load it on the page. You're manipulating DOM - respect the game - wait for the DOM to load.

Related

Scope error in JavaScript

I was playing with input[range] in html with javascript. I came up with a problem. Here is the code:-
<html>
<head>
<meta charset="utf-8">
<title>Slider and range !!</title>
<script type="text/javascript">
let div = document.getElementById('display');
function foo(value) {
div.innerHTML = value;
}
</script>
<style>
input[type='range']{
border : 5px grey solid;
border-radius: 10px;
}
</style>
</head>
<body>
<input id="input" type="range" min = '0' max ='100' step="10" oninput="foo(this.value)" >
<div id="display"></div>
</body>
</html>
Here in webconsole div is shown undefined but if I declare the function as this:-
function foo(value) {
let div = document.getElementById('display');
div.innerHTML = value;
}
The code is working.Why is this working like this way?Please help Thank you.
Let's understand the how DOM parsing works on Browser.
When we load any document/HTML on DOM/Browser, It starts document parsing. It iterated elements and creates a DOM tree. It starts from TOP, goes to the header and check for other resources and execute them one by one.
Here when you wrote
let div = document.getElementById('display');
in simple script tag without wrapping it into any function, it executed first without getting your DOM loaded.
Which means, the parser is looking for DIV by its ID which is not present yet on the browser. Hence it is undefined. Now the question is how does it work inside the function?
Functions in JavaScripts gets executed on DOMContentLoaded. This is similar to jQuery ready(). This ensures that the DOM has been ready and each element on the browser has been traversed and is now in DOM tree.
Now, you probably thinking how it works when we put this code at the bottom of the page? like
<html>
<head></head>
<body>
YOUR HTML
</body>
<script type="text/javascript">
//YOUR JS CODE
</script>
So when we insert JS which is looking for an element in DOM at the top of the page in head tag and if there is an error in getting the JS executed (like in your case the JS is looking for DIV which is not on DOM yet) it will stop the execution of DOM unless the script resolved the error.
Hence when we place JS code at the bottom of the page, the browser has already parsed all the page element and the DOM tree is ready. Thus, any element is now accessible by JS.
Which means, if you write your above code at the bottom of the page, it will get the element without error.
Footnote:
Read more about how JavaScript works on browser
https://javascript.info/onload-ondomcontentloaded
Where should I put <script> tags in HTML markup?
Hope this helps,
Thanks
-AG
check this, give the script at the bottom of the page,
means initialize the div variable, only after rendering the page
<html>
<head>
<meta charset="utf-8">
<title>Slider and range !!</title>
<script type="text/javascript">
let div;
function onLoadFunction() {
div = document.getElementById('display');
}
function foo(value) {
div.innerHTML = value;
}
</script>
<style>
input[type='range'] {
border: 5px grey solid;
border-radius: 10px;
}
</style>
</head>
<body onLoad="onLoadFunction()">
<input id="input" type="range" min='0' max='100' step="10" oninput="foo(this.value)">
<div id="display"></div>
</body>
</html>
You try to access the display element before it is loaded. Either you will have to place your script lower in the HTML file or make it execute at the onLoad function of the document.
document.onload = function() {
//run your code here
}
Not working first approach because your trying access the DOM element which not loaded yet. let div = document.getElementById('display'); by this code you trying to access immediately. When the JS code in global scope it is parse line by line and all lines execute immediately.
But following code is working fine because here you accessing the DOM element in function scope and function only running when range value are changing in the meantime the DOM is already loaded and available to manipulate.
function foo(value) {
let div = document.getElementById('display'); // Now `display` available, so no error
div.innerHTML = value;
}

HTML and JavaScript in separate files - newbie alert

OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.

Javascript: Does not change the div innerHTML

I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix

Result of getElementById is null?

Just struggling with a Javascript class being used as a method for some cometishian code, how do I have a constructor for this code? The following code is invalid:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="Stylesheet" href="gStyle.css" />
<script type="text/javascript" language="javascript">
// Gantt chart object
function ganttChart(gContainerID) {
this.isDebugMode = true;
this.gContainer = document.getElementById(gContainerID);
if (this.isDebugMode) {
this.gContainer.innerHTML += "<div id=\"gDebug\">5,5 | 5.1</div>";
}
}
var myChart = new ganttChart("chart1");
</script>
</head>
</html>
<body>
<div id="chart1" class="gContainer"></div>
</body>
</html>
this.gContainer is null
That is because you are running the script before the page is ready, i.e. chart1 doesn't exist yet when you call new ganttChart("chart1");. Wrap the code inside window.onload = function() { } or run it at the bottom of the page.
The problem is that your script is running too early, it's looking for an element that doesn't exist in the DOM yet, either run your script onload, or place it at the end of the <body> so your id="chart1" element is there to be found when it runs.
Problem is that you run your code before the page has loaded yet, and thus the DOM element with id chart1 does not exist at the moment the code is executed.
use
window.onload = function(){myChart = new ganttChart("chart1");};
Note that using window.onload like that will override all previously stated window.onload declarations. Something along the following lines would be better:
<script type="text/javascript">
var prevOnload = window.onload || function () {};
window.onload = function () {
prevOnload();
// do your stuff here
};
</script>
Also, untill al images are fully loaded onload will not trigger, consider using jquery & $(document).ready or similar.
:)
Regards,
Pedro

how do I automatically execute javascript?

how do I automatically execute javascript?
I know of <body onLoad="">, but I just thought maybe there is another way to do it?
html:
<html><head></head><body><div id="test"></div></body></html>
javascript:
<script>(function(){var text = document.getElementById('test').innerHTML;var newtext = text.replace('', '');return newtext;})();</script>
I wanna get the text within "test", replace certain parts, and then output it to the browser.
Any ideas on how to do it? I'd appreciate any help. Thanks.
If you don't want to use <body onload> which is good choice in terms of obtrusive javascript, you can separate that and put you code like this:
window.onload = function(){
// your code here
};
Alternative:
Place your javascript code at the bottom of the page.
Place the script at the bottom of the page, outside the closing body tag..
It's REALLY easy! If you have a script in your "head" block, with no function id, it will run automatically as soon as the web page loads. For example:
<head>
<meta charset="UTF-8">
<title>Redirection to www.mywebsite.org</title>
<!-- This script initiates an automatic web page redirection, as the page is loaded -->
<script type="text/javascript">
window.location = "http://www.mywebsite.com/"
</script>
</head>
If you don't want to use jQuery, use native window.onload method:
<script type="text/javascript">
function ReplaceText() {
document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/abc/g, "def");
}
window.onload = ReplaceText;
</script>
Used on the code:
<div id="test">abc abc</div>
Will give this output:
def def
A quick way, if you just want to debug, would be move what you want to execute outside of a function.
<script type="text/javascript">
var text = document.getElementById('test').innerHTML;
var newtext = text.replace('', '');
alert(newtext);
</script>
NB. I'm not sure what you hope to achieve with text.replace('', '') ?

Categories