Cannot use document.getElementById() in global scope - javascript

When I try this on the global scope:
document.getElementById("p1").innerHTML ="Howdy mate";
It does not work and firebug reports the error:
TypeError: document.getElementById is null
But the same instruction works well when inside a function:
function sayHello(){
document.getElementById("p1").innerHTML ="Howdy mate";
}
I am yet to find any literature to explain this behaviour. Can anyone help?
EDIT: #All, the correct error message was
document.getElementById("p1") is null
not
Window.getElementById("p1") is not a function
as earlier stated. I have corrected.

could be you're calling document.getElementById("p1").innerHTML ="Howdy mate";
before the element is loaded?
http://jsbin.com/abejiz/1/edit vs http://jsbin.com/abejiz/2/edit

#All, I revised my code following #user2264587's answer. The problem was that I had my javascript code loaded to the <head> tag of the document while the <p> element with id="p1" was located in the <body>. So the javascript instruction was actually being executed before the <p> element was loaded. I have now placed code inside <body> and after <p>:
<body>
...
<p id="p1"><p>
<script>
document.getElementById("p1").innerHTML ="Howdy mate";
</script>
</body>
It works fine.

Related

Finding number of children of an element returns 'null' error

I am trying to find the number of children of a node by pure 'javascript' but getting unexpected error.
HTML:
<html>
<head>
<script>
var a = document.getElementById('div1').children.length;
console.log(a);
</script>
</head>
<body>
<div id="div1">
<p>This is para1.</p>
<p>This is para2.</p>
</div>
</body>
</html>
ERROR:
TypeError: Cannot read property 'children' of null
But, I can clearly see that my div has 2 children nodes. Can someone help?
You should put your code to onload event
window.onload = function () {
var a = document.getElementById('div1').children.length;
console.log(a);
}
or put your script before </body>, because you are trying get DOM node before it will be created
Your problem is caused by the order of events during the page construction in your browser.
An HTML is parsed and evaluated synchronously, in order. Scripts are evaluated as soon as the occur in the HTML. When your script (document.getElementById('div1')...) is evaluated, the div1 doesn't exist yet (it wasn't seen by the parser yet), and so the result is null and you get the exception.
That's why it's recommended to put inline script tags in the end of the HTML document, immediately before the body closing tag (</body>).

How to make an anchor tag's href invoke an anonymous function?

I'm working on a cross-site scripting attack on an internet forum where links can be put in post like
[url]http://google.com[/url]
which then gets surfaced as
http://google.com
on the forum's thread. If possible, I want to use the technique of invoking JavaScript functions through the href, i.e.
<script type="text/javascript">
function sayHello ( )
{
alert("Hello");
}
</script>
Clicking here alerts "Hello"
but since I don't have any way of using predefined JavaScript functions, I'm wondering if I can put anonymous functions in there, e.g.
Clicking here alerts "Hello"
I've tested this out in Notepad with the simple page
<html>
<head>
</head>
<body>
<div>
<p>Clicking on this will alert "Hello""</p>
</div>
</body>
</html>
but it didn't work.
Any suggestions for me?
Use an IIFE:
Click here
Although there's not too much difference from doing this without the IIFE, just as top-level JS code:
Click here
The only significant difference is that you can declare local variables within the function.

Uncaught ReferenceError: [functionName] is not defined

Sincere apologies if this has already been covered. I've been trawling StackOverflow for a while now and I cannot find anything that will fix my issue. Many people have this error, but theirs seem to be derived from syntax errors and the suchlike. I (nor JSLint) can't find any such errors, so I'm rather stumped.
The following code (from the W3Schools page) does work:
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
However, my code does not work:
<head>
<!--SNIP-->
<script language="text/javascript">
function iconclicked() {
alert("Yay!");
}
</script>
</head>
<body>
<div class="icon" id="misc" onclick="iconclicked()"></div>
</body>
This produces the "Uncaught ReferenceError: iconclicked is not defined" error.
But, and correct me if I'm wrong, function iconclicked() {...} is what defines the function and it is clearly present. Additionally, moving the JScript to be within the <body>tag does not fix the problem, regardless of whether to script is before or after the div. If you were to substitute the div for another element (a button, image, text, etc) or to call the function a different way (e.g. via onload) the code does not work.
I thought that perhaps it was the rest of the code on my page causing something funny to happen, so I headed over to JSFIDDLE and popped the old W3Schools code in there. Lo and behold, "Uncaught ReferenceError: myFunction is not defined". JSFDDLE link
Edit: turns out this is just due to the fact I didn't choose 'no wrap' in the JSFIDDLE options - thanks Peter Healy :)
But if you go ahead put the JS inside <script> </script> tags in the HTML section of JSFIDDLE, there is no such problem and the code works as intended. JSFIDDLE link
I figure maybe this is a scope problem, but I can't for the life of me work out what it is specifically. Hopefully someone out there with more experience has the answer!
There is no language of "text/javascript", that is the type.
Change
<script language="text/javascript">
to just
<script>
Do not worry about the language or type attributes. Language has been deprecated.
It's actually <script type="text/javascript">, with a type attribute, not language:
<head>
<!--SNIP-->
<script type="text/javascript">
function iconclicked() {
alert("Yay!");
}
</script>
</head>
<body>
<div class="icon" id="misc" onclick="iconclicked()"></div>
</body>
The language attribute went out of style a while ago.
It's how JSFiddle wraps up your JS. Choosing No Wrap option on left hand side will solve it for you.
Read here: no wrap
Edit: remove text/javascript

Returning from JavaScript function to HTML Body

I am calling a JavaScript function from the HTML Body using the onload event. The JavaScript function executes successfully but the HTML Body contents are not displayed.
I believe, there is an issue with returning from the JavaScript to the HTML Body.
Here is how the code looks like:
<html>
<script type="text/javascript">
function display()
{
document.write("You just executed JavaScript code");
return true;
}
</script>
<body onload="display();">
<p>We are in HTML now</p>
</body>
</html>
This will display the text, "You just executed JavaScript code" in the browser. But the innerHTML of tags is not displayed.
I modified the onload event in tag as:
<body onload="return display();">
And, even this executes only the JavaScript.
If you just want to show the message as alert try this.
<script type="text/javascript">
function display()
{
alert("You just executed JavaScript code");
return true;
}
</script>
</head>
<html>
<body onload="display();">
<p>We are in HTML now</p>
</body>
else
<script type="text/javascript">
window.onload=function()
{
document.getElementById("js").innerHTML = "You just executed JavaScript code";
return true;
}
</script>
<body>
<p id="js"></p>
<p>We are in HTML now</p>
</body>
</html>
As per https://developer.mozilla.org/en/document.write
Once the document has finished loading, calling document.write() will actually first call document.open(), which replaces the currently loaded document with a new Document object. So what you're doing with your code is replacing the original document with one that only contains the string 'You just executed javascript code'.
So if you want to use document.write to place text inline, you would have to use it like so:
<html>
<body>
<p>We are in HTML now</p>
<script>
document.write('You just executed javascript code');
</script>
</body>
</html>
If you want to insert text into the document after it has finished loading, you'll need to use another method, like innerHTML.
Document.write is replacing the contents inside your body tag.
Try something like this.
<html>
<script type="text/javascript">
function display()
{
document.getElementById("text-from-js").innerHTML = "You just executed JavaScript code";
return true;
}
</script>
<body onload="display();">
<p>We are in HTML now</p>
<p id="text-from-js"></p>
</body>
</html>
As the previous answers said. document.write cannot be used for your purpose. And I strongly
recommend that you don't use it anywhere. Its a bad practice.
For your purpose prepending/appending to document.body.innerHTML
ex: document.body.innerHTML += 'You just executed javascript code';
or something like
document.body.appendChild(document.createTextNode('You just executed javascript code'))
should do.
Hi Neon Flash,
I have done some work on your problem.I also research about where is the problem then i found some interesting points hope this will help you
Check here
or you can use
Usually, instead of doing
document.write
someElement.innerHTML
document.createElement with an someElement.appendChild.
You can also consider using a library like jQuery and using the modification functions in there: http://api.jquery.com/category/manipulation/

Call javascript on checkbox onclick

I don't understand what I'm doing wrong here. I just want my function to be called when I click the checkbox. Replacing the function call with alert() works, am I referencing my function incorrectly?
<html>
<head></head>
<body>
<script type="text/javascript">
function select(a){
document.getElementById("myDiv").innerHTML=""+a;
}
</script>
<input type="checkbox" onclick="select(1)">
<div id="myDiv">hi</div>
</body>
</html>
Thanks
Change the function name [e.g. selectFun]. select seems to be reserved keyword
This puzzled me as it looked ok to me too, So ran through the usual tests, eventually tried changing the function name and that worked fine.

Categories