Actions in a javascript file not being taken - javascript

I'm trying to get to work a page that says the date with a "index.html" including a javascript file. However, I don't know if I'm missing something here but when testing it, it won't appear in the index.html.
I just want the date to be shown with the code of the js.
Here's the code of the index.html:
<!DOCTYPE html>
<head>
<title>Test</title>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/date.js"></script>
</head>
<script>
<p id="test1"></p>
</script>
And here's the code of the javascript file:
var isDate = new Date();
document.getElementById("test1").innerHTML = isDate.getDate;
As you can see, I tried puting script tag around the p tag and dindn't work either.
This is really basic javascript but it's like really hard for me to start off in a new language.
Thanks.

try correcting your HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="scripts/date.js"></script>
</head>
<body>
<p id="test1"></p>
</body>
</html>

This is the code your looking for:
<div>
<p id="test1"></p>
</div>
<script>
var isDate = new Date();
document.getElementById("test1").innerHTML = isDate.getDate();
</script>

use the defer attribute like:
<script type="text/javascript" src="scripts/date.js" defer></script>
then it should work just fine.
The reason for this is that putting the script tag in the head will run the script
before the content of the body is parsed so using defer will make the script
run after all the questions have been parsed.

The format for the HTML document is incorrect. Surrounding <p> with <script> doesn't make sense because <script> is for Javascript code whereas you wanted to create HTML elements. You want <p> to be the child of <body> to display the element.
As for using the Date function in JavaScript, here is a related question to get the format correct.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/date.js"></script>
</head>
<body>
<p id="test1"></p>
</body>
<script>
var isDate = new Date();
document.getElementById("test1").innerHTML = isDate.getDate();
</script>
</html>

so console.log will be your new best friend, Throw that into the file and see if your console shows any of the ouput. my guess is that you
Also you did not put the p tag into a body, also dont wrap html elements in script tags.
<!DOCTYPE html>
<head>
<title>Test</title>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/date.js"></script>
</head>
<body>
<p id="test1"></p>
</body>
</html>
and scripts/date.js
window.onload = function() {
var currentDate = new Date();
var paragraph = document.getElementById("test1");
if (paragraph) {
paragraph.innerHTML = currentDate.getDate();
}
}

Related

my code is working on codepen but not in my browser. i wanted to getelementbyid and then then that element on console

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Assignment 4</title>
<script src="script.js"></script>
</head>
<body>
<h1>Biryani</h1>
<h2 id="hello">Rohan</h2>
<p>Biryani is Pakistan's special dish. Main Ingredients are rice and chicken.</p>
</body>
</html>
script.js
<-- this script is used to getelementbyid "hello" and then displaying on console.-->
var myname = document.getElementById("hello");
console.log(myname.innerHTML);
const el = document.querySelector('h2');
el.textContent = 'Assignment 4';
The code is correct. You just need to move your script tag just before you close the body tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Assignment 4</title>
</head>
<body>
<h1>Biryani</h1>
<h2 id="hello">Rohan</h2>
<p>
Biryani is Pakistan's special dish. Main Ingredients are rice and chicken.
</p>
<script src="./script.js"></script>
</body>
</html>
You should include js below of your element definitions.
Browser is compiling html scripts from top to below. If you included js code before all elements defined then that catch nothing and it returns error.
...
// your elements are defined here.
<script src="script.js"></script>
</body>

Why does <script> appear in <body> when I defined it outside of <body>?

I'm busy pumping out some web projects from the Odin Project. Anyway, I'd like to adhere to the software engineering process of taking small steps and testing them. Now, for instance, I'd like to see the output of document.querySelector("body"). It is my understanding that I should place the tag somewhere, I'm not too sure what the best place is. The StackOverflow posts on this topic are quite ambiguous. Here's my code:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Etch-A-Sketch</title>
<meta charset="UTF-8"/>
</head>
<body>
</body>
<script type="text/javascript" src="createDOM.js"></script>
</html>
createDOM.js:
const body = document.querySelector("body");
console.log(body);
Console:
<body>
<script type="text/javascript" src="createDOM.js"></script>
</body>
Me:
$ ????????
It is the way webengine play with source. Most ( and almost all ) webengine put everything into body that can be ( i.e following the standard ) because body is taken as subroot for DOM structure
Wrapp your script inside the body tag, at the end.
<!DOCTYPE html>
<html>
<head>
<title>Etch-A-Sketch</title>
<meta charset="UTF-8"/>
</head>
<body>
<script type="text/javascript" src="createDOM.js"</script>
</body>
</html>

Injecting data into HTML tag

I'm developing an extension for Microsoft Edge and have learned from the docs here https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/creating-an-extension#writing-a-more-complex-extension that I can use Javascript for data manipulation.
For some reason though, when I try to modify a DOM element like this:
<!DOCTYPE html>
<html>
<body>
<p></p>
<script type='text/javascript'>
document.getElementsByTagName('P')[0].innerHTML = 'something';
</script>
</body>
</html>
I get the desired result in any HTML / JAVASCRIPT interpreter but when I try to test it out in the extension the DOM manipulation isn't working. The p element isn't populated with 'something'. The manifest.json file is included in the extension folder I'm just not including it here as it's not relevant to the question.
How should I go about this ?
Update:
window.html:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='window.css'>
</head>
<body>
<div><p></p></div>
<script src="window.js"></script>
</body>
</html>
window.js:
window.onload() {
document.getElementsByTagName('P')[0].innerHTML = 'hakuna matata';
};
You should import the JavaScript function using <script> tag like below:
In myfunction.js file of js folder:
document.getElementsByTagName('p')[0].innerHTML = 'something';
In html file:
<!DOCTYPE html>
<html>
<body>
<p></p>
<script src="js/myfunction.js"></script>
</body>
</html>
I tested it in Edge extension: If we use the JavaScript function directly in the html page then it doesn't work. If we use a link to the js file then it works.

Changing a div with javascript

I already fail at a seemingly basic task in javascript - changing a div's content by a script. Please help me understand where I am going wrong. Here is a minimal example that's not working for me:
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById('id').innerHTML = "test";
</script>
</head>
<body>
<div id="id" >blub</div>
</body>
</html>
The Problem with you code it that the JavaScript code is executed before the div part is loaded fully. To fix this change you code to:
<!DOCTYPE html>
<html>
<head>
<script>
function changeDiv()
{
document.getElementById('id').innerHTML = "test";
}
</script>
</head>
<body onload="changeDiv();">
<div id="id" >blub</div>
</body>
</html>
The onload event will only fire when the html is fully loaded.
HTML files load starting at the top to the bottom of the html.
In your example, the javascript executes before the <body> tag exists in the DOM.
Moving the javascript to below the relevant html makes it work as you would expect.
Another option would be to keep the script inside the <head> but delay it from executing until the DOM is loaded
window.onload = function() {
document.getElementById('id').innerHTML = "test";
};
https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="id" >blub</div>
<script>
document.getElementById('id').innerHTML = "test";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="id" >blub</div>
<script>
document.getElementById('id').innerHTML = "test";
</script>
</body>
</html>
put your script after the div.
You need to use window.onload to call your code when html is fully loaded:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
document.getElementById('id').innerHTML = "test";
};
</script>
</head>
<body>
<div id="id" >blub</div>
</body>
</html>
Your Dom is no not loaded.. Place your script tag at the end before
Just add the script tag before closing the body. It'll work.
You have to write the Javascript after the div-Tag. First the DOM needs to be loaded and after you can change the content inside the DIV.
Place your Javascript before the closing-body Tag

Cannot set property 'innerHTML' of null

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
I thought I understood innerHTML and had it working before.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</head>
<body>
<div id="hello"></div>
</body>
</html>
You have to place the hello div before the script, so that it exists when the script is loaded.
Let us first try to understand the root cause as to why it is happening in first place.
Why do I get an error or Uncaught TypeError: Cannot set property
'innerHTML' of null?
The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.
How can you make it work as before?
You want to show the hi message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:
Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with id hello already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type ="text/javascript">
window.onload = function() {
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
}
</script>
</head>
<body>
<div id="hello"></div>
</body>
</html>
You could tell javascript to perform the action "onload"... Try with this:
<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
Just put your JS in window.onload
window.onload = function() {
what();
function what() {
document.getElementById('hello').innerHTML = 'hi';
};
}
The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Javascript looks good. Try to run it after the the div has loaded. Try to run only when the document is ready. $(document).ready in jquery.
Here Is my snippet try it. I hope it will helpfull for u.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = '<p>hi</p>';
};
</script>
</body>
</html>
You could try using the setTimeout method to make sure your html loads first.
The root cause is: HTML on a page have to loaded before javascript code.
Resolving in 2 ways:
1) Allow HTML load before the js code.
<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
}
</script>
//or set time out like this:
<script type ="text/javascript">
setTimeout(function(){
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
}, 50);
//NOTE: 50 is milisecond.
</script>
2) Move js code under HTML code
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.
If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.
I hope this was useful to you.
This error can appear even if you load your script after the html render is finished. In this given example your code
<div id="hello"></div>
has no value inside the div. So the error is raised, because there is no value to change inside. It should have been
<div id="hello">Some random text to change</div>
then.
Add jquery into < head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Use $document.ready() : the code can be in < head> or in a separate file like main.js
1) using js in same file (add this in the < head>):
<script>
$( document ).ready(function() {
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
});
</script>
2) using some other file like main.js (add this in the < head>):
<script type="text/javascript" src="/path/to/main.js" charset="utf-8"></script>
and add the code in main.js file :)
You need to change div into p. Technically innerHTML means it is inside the <??? id=""></???> part.
Change:
<div id="hello"></div>
into
<p id="hello"></p>
Doing:
document.getElementById('hello').innerHTML = 'hi';
will turn
<div id="hello"></div> into this <div id="hello">hi</div>
which actually does not make sense.
You can also try to change:
document.getElementById('hello').innerHTML = 'hi';
into this
document.getElementById('hello').innerHTML='<p> hi </p> ';
to make it work.
The error is self-explaining it is not getting the HTML tag in which You want to set the Data So make tag available to JS then only You can set Data to that.
No doubt, most of the answers here are correct, but you can also do this:
document.addEventListener('DOMContentLoaded', function what() {
document.getElementById('hello').innerHTML = 'hi';
});
There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.
In my case I had a missing close div as shown below
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div> //I am an open div
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM
Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.
I have moved my <script> tag below the <body> tag. Let’s try
<body>
<p>The time is <span id="time"></span>.</p>
</body>
<script>
// Allways keep script at end for date and time object //
var d = new Date();
document.getElementById("time").innerHTML = d;
</script>
This happened to me when using Django template tags on an if-check to see if there was a value available for a field - if no value I removed everything associated with the value from the page to keep things neat The only problem was the content I removed included the div and id I was trying to work with! If there was a value present there was no issue as the div that contained the id I was working with was present. If there was no value I received the error. Once it hit me that's what was going on then easy fix to just add the div in there if the if-check is false.
Before
{% if model.value %}
<div id='my-id'>{{model.value}}</div>
{% endif %}
After
{% if model.value %}
<div>{{model.value}}</div>
{% else %}
<div id='my-id'></div>
{% endif %}

Categories