I cannot print a helloworld message using Javascript in my HTML document. Let me explain my problem from beginning to end one-by-one.
I'm using the latest version of Microsoft Edge as my default web browser.
Using a simple notepad, I just created a simple HTML document named chandan.htm and saved it to my hard disk.
I also included the script tag in the body of the HTML document in an intent to print the "hello world" message in java script code.
I share the simple HTML code, in which a simple Javascript code is embedded to print the "hello world" message:
<!DOCTYPE html>
<html>
<head>
<title> hello chandan how are you and what are you doing</title>
</head>
<body>
<script>
document.write("hello world ! ");
</script>
<h1>politics</h1>
</body>
</html>
When I run the HTML document in my Microsoft Edge browser, I cannot see the "hello world" message, that I have specified to print on the HTML document inside the script tag. I also gave a try by running this HTML document in Google Chrome and Internet Explorer hoping that it would print the "hello world" message once on the browser, but this thing did not happen at all. Instead, I could see only the HTML code, such as the text of the title, and the text of the heading tag of the HTML document; not "hello world" message from Javascript.
Before the date of May 30, 2020, everything was fine. The instructions of the Javascript, which were specified within the script tag of HTML document, were executed properly. I was able to print the "hello world" message using the Javascript command document.write("..."). I could also see the "hello world" message directly on the screen. but after the date 30th May, 2020, I could not execute any Javascript code in any of my browser. 5-6 days after, when I tried to print the same "hello world" message again on my browser, the code was not executed and I cannot see the "hello world" message on my screen. could you resolve this problem?
I also tried to debug this problem at my level. What I double-clicked on the "chandan.htm" document, which opened the document in Edge, which is my default web browser. when I did not see the "hello world" message, I simply pressed "CONTROL-Shift-i" to open the console window. On the console prompt window, when I typed document.write("hello world") and pressed "enter", then the console prints "undefined". That's it. so please help me to solve this problem soon.
When you save a file in notepad, .txt is automatically appended to it and you can't see the extension due to file explorer's default settings. At the bottom of the save dialog, there should be a dropdown with the label "Save as type", and you want to click it and select "All files (*.*)", so .txt isn't automatically appended to it. Then, when you open it, it should appear as html and not as text.
The problem is most people don't have the basics covered. The full working example is posted below though I'm going to make some clarifications first.
There are separate parsers (software that takes code and determines what to do with it) for HTML and XML. I use the XML parser with HTML5 code so I gain the benefit of the latest technology with the much stricter XML parser. I've seen someone waste three days trying to figure out why Safari wouldn't properly style while all other browsers worked fine; he discovered he was missing a quote on an attribute. Using the XML parser the page immediately breaks and you get an error message.
The XML parser works best in Gecko browsers such as Waterfox and Firefox. Other browsers render up to an error in the code.
Stricter code might seem more difficult though it's been a massive boon for me. All the stuff I had to figure out has long been well documented presuming you know how to ask the questions you'll naturally encounter.
Even if you use the HTML parser you should never use document.write or innerHTML as they're proprietary and really buggy. Those who disagree do not test browsers properly.
Never put script elements in the body element, it leads to weak code that breaks easy.
Use the defer="true" attribute/value on script elements in the head as this will require the HTML/XML to finish loading instead of executing a script before some of the expected HTML appears.
Spend time familiarizing yourself with JavaScript (and HTML/CSS) functions and methods to get an idea of how much is available to work with.
Avoid frameworks and libraries and use normal pure JavaScript. You will save yourself vast amounts of frustration once you have the experience.
Use Notepadd++ to edit files, Notepad in Windows adds a BOM (Byte Order Mark) that causes havoc with XML parsers and other aspects of code. Plus you can theme and get nifty things like bracket highlighting.
example.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<script type="application/javascript">
//<![CDATA[
window.onload = function(event)
{
if (confirm('Would you like to add some text to the paragraph?'))
{
document.getElementById('example1').textContent = 'Hello World!';
}
}
//]]>
</script>
<style type="text/css">
</style>
</head>
<body>
<p id="example1"></p>
</body>
</html>
Related
I am learning JavaScript and I am using Atom (Text Editor).
On my HTML file I got only this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<button id="displayTodosButton">Display Todos</button>
<button>Toggle Todos</button>
</body>
</html>
On my javascript file, I am simply trying to access the "Display todos" button using this:
var displayTodosButton = document.getElementById('displayTodosButton')
I was watching a video, and the instructor is using plnkr.co, and he accesses the button just fine, yet on Atom I get the "ReferenceError: document is not defined"
How can I fix this?
yet on Atom I get
If you really mean that Atom, your text editor, is highlighting it and showing you a warning that document is undefined, it's just that Atom doesn't realize you're running that code in a browser context where document will be defined.
It probably has a setting where you can tell it that you'll be running the code in a browser, so it can assume the default set of globals (window, document, etc.).
If the code in script.js is just what you've shown, although the error Atom is showing you won't be a problem (because in the browser, document will not be undefined), you'll get null back from getElementById because your code runs before the element exists. Again, this is assuming that code is on its own, not (say) inside a DOMContentLoaded handler or similar.
Unless you have a good reason to do it (and there aren't many), putting script elements in the head is an anti-pattern. Put them in body, right at the end, just prior to the closing </body> tag. That way, any elements defined above them will have been created by the browser before your code runs.
You have hit some menu option or key combination which is trying to execute the JS file using Node.js.
Your code, however, is designed to run, embedded in a web page, using the APIs supplied by web browsers.
Web browsers, under those circumstances, will provide a document object. Node.js will not.
You need to open the HTML document in a web browser. The open in browser extension might be useful.
You can see any error reports using the Developer Tools that every major browser supplies.
(NB: The first error you will then encounter is explained by this question and answer).
It looks like you are trying to run the JS code with the "script" package in atom (which is in a NodeJS context). What you actually want to do, is to run it in your web browser. So just open index.html in your favorite browser and see the magic :)
I am learning JavaScript and I am using Atom (Text Editor).
On my HTML file I got only this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<button id="displayTodosButton">Display Todos</button>
<button>Toggle Todos</button>
</body>
</html>
On my javascript file, I am simply trying to access the "Display todos" button using this:
var displayTodosButton = document.getElementById('displayTodosButton')
I was watching a video, and the instructor is using plnkr.co, and he accesses the button just fine, yet on Atom I get the "ReferenceError: document is not defined"
How can I fix this?
yet on Atom I get
If you really mean that Atom, your text editor, is highlighting it and showing you a warning that document is undefined, it's just that Atom doesn't realize you're running that code in a browser context where document will be defined.
It probably has a setting where you can tell it that you'll be running the code in a browser, so it can assume the default set of globals (window, document, etc.).
If the code in script.js is just what you've shown, although the error Atom is showing you won't be a problem (because in the browser, document will not be undefined), you'll get null back from getElementById because your code runs before the element exists. Again, this is assuming that code is on its own, not (say) inside a DOMContentLoaded handler or similar.
Unless you have a good reason to do it (and there aren't many), putting script elements in the head is an anti-pattern. Put them in body, right at the end, just prior to the closing </body> tag. That way, any elements defined above them will have been created by the browser before your code runs.
You have hit some menu option or key combination which is trying to execute the JS file using Node.js.
Your code, however, is designed to run, embedded in a web page, using the APIs supplied by web browsers.
Web browsers, under those circumstances, will provide a document object. Node.js will not.
You need to open the HTML document in a web browser. The open in browser extension might be useful.
You can see any error reports using the Developer Tools that every major browser supplies.
(NB: The first error you will then encounter is explained by this question and answer).
It looks like you are trying to run the JS code with the "script" package in atom (which is in a NodeJS context). What you actually want to do, is to run it in your web browser. So just open index.html in your favorite browser and see the magic :)
I have written javascript that I am currently excecuting in the devtools of chrome (the console section). Is there any way to do that in javascript without me having to open the page, open the console, type it in, etc. I would be doing this from an external page. If this is confusing here is an example:
mypage.com
<script>
function myFunc(){return document.getElementById("hi")};
</script>
targetpage.com
<p id="hi">Hello world</p>
In this case, how can I run myFunc on targetpage.com from mypage.com?
Web browsers (by design) explicitly prohibit what you are trying to achieve. The JavaScript can only run on a page that originated from the same server.
The only way to "run" the code from a different source is via eval()
The way eval() works is you provide is with a JavaScript "text" that it will dynamically execute.
As mentioned in the comments - eval() is very evil.
eval() executes code provided as a text. For instance:
var code = "var i = 10; alert(i);";
eval(code);
The above lines will pop an alert window displaying "10".
The main point of the answer is: you cannot do what you are hoping to achieve.
My javascript was working properly and then all of the sudden it wasn't. Chrome give me the Uncaught SyntaxError: Unexpected token ILLEGAL error on line 1 of my JS file called para2.js. I removed script from the file except for the following and I still get the error:
$( window ).ready(function() {
});
My jQuery file is included in the head of my document:
<script src="../shared/jquery.js" type="text/javascript"></script>
<script src="js/para2.js" type="text/javascript"></script>
When I look at my js file in Chrome developer tools on the Sources tab, it displays the script in Chinese:
兪敵祲搨捯浵湥⥴爮慥祤昨湵瑣潩⡮笩⥽
When I view the source of the js file, it looks fine. I have read similar posts that say copy and pasting from JSFiddle can include some hidden characters that may cause it, but I have started from scratch writing this file from a blank text file and copy and pasting nothing. It is strange that it was working and now it is not. Did my server get hacked or something? And help is appreciated.
You should use the charset attribute to indicate which charset you are using.
<script src="../shared/jquery.js" type="text/javascript" charset="UTF-8">
I had the same problem with jquery-1.5.1.min.js. Chrome kept evaluating it as Chinese (scripts worked fine in IE). I finally solved the problem by re-encoding the .js files using "convert to UTF-8" in Notepad++. Note, not UTF-8 without BOM, but UTF-8.
I am forced to use a web application written (over a decade ago I'm guessing) for IE6 and only works with IE (newer versions in quirks mode). I have been able to repair some of the more egregious javascript with a Safari extension that injects scripts to detach event handlers and replace them with DOM compliant versions.
I am now turning my attention to annoyances rather than the downright broken. The heavy handed use of alerts to inform the user of progress is painful. I thought it would be a fairly nice addition to my extension to override the window.alert function with some css popovers, but the challenge I am having is with pages that are sent back after an http post, where the first thing they do is display a success (or failure) alert.
According to this Apple documentation "a Start Script executes when the document has been created but before the webpage has been parsed". I would have thought that if the page hadn't been parsed, the scripts in the page's body's script tags wouldn't run, but this is not the behaviour I am seeing. Instead, it appears that any scripts in the page returned from the post response execute before my start script even loads.
To test this I have a very simple start script that logs to the console location.href and tries to replace window.alert with console.log.
The injected start script:
console.log(window.location.href + "loaded killAlert.js") ;
window.alert=function(str) { console.log(str) ; }
The test web page:
<html><head></head>
<body>
<script>alert("this is an alert message") ;</script>
nothing to see here... move along.
</body>
</html>
What happens is that when loading a test page with a script embedded, the alert executes before anything is written to console.log.
My questions—
When do start scripts actually get called?
Is there any way I can get them to execute before any scripts on the page?
While this seems like it should be fairly straight forward, but so far I haven't been able to find a way around the problem through reading documentation, search or experimenting. I'm hoping someone else has solved something similar.
<head>
<script>
(function() {
console.log(window.location.href + "loaded killAlert.js") ;
window.alert=function(str) { console.log(str) ; }
})();
</script>
</head>
Try calling it anonymously, it will execute the script immediately after the creation. Hope it helps.