This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
First I'm sorry, because I'm certain that this has been asked many times, I just don't know how to search for this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<form>
<button type="button" onclick="hello()">test1</button>
<button type="button" id="test2">test2</button>
<h1 id='myText'></h1>
<script type="text/javascript">
function hello() {
document.getElementById('myText').innerHTML = 'test1';
}
document.getElementById('test2').onclick = function(event) {
document.getElementById('myText').innerHTML = 'test2';
}
</script>
</form>
</body>
</html>
This is my code. Before this version the whole script-tag was within the head area, and only test1 worked, test2 did nothing.
Can you point me on where to read up on why that is so?
Also, is there a preferred method of the two, to trigger an event?
It's the order in which the elements are processed.
In very simple terms: stuff in <head> loads up before the stuff in <body>, likewise, stuff at the top of <body> will load before stuff at the end of <body>. For this reason, where you're trying to grab an element with an ID of test2, your #test2 event handler will only work when the #test2 button has been loaded before your <script>; otherwise it simply doesn't exist on the page at this point.
Related
This question already has answers here:
javascript function name cannot set as click?
(6 answers)
Closed 6 months ago.
I have a relatively trivial problem, that has caused me to get stumped for a few hours
I am trying to get my button to call a JavaScript function that logs to console
Here is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="script.js"></script>
<meta charset="UTF-8">
<title>McKinsey Prep</title>
<div>
<button onclick="click()">Some Button</button>
</div>
</head>
<body>
</body>
</html>
The button here is calling the click() method in this JavaScript file
console.log("Code has reached here")
function click(){
console.log("Button was clicked REEEEe")
}
The script.js file only has this function, I DO NOT want to execute code in my HTML document
When I run my index.js it prints the first print statement but the console.log in the function call does not appear on console when I click my button
NOTE
I am left clicking my index.html and pressing run to run my code.
What could be the issue?
Click() is a reserved name, you can't use it on a function because there is a native method on JS with that name.
Change the name of your function and try again.
Here is an example
<button onclick="clicked()">Some Button</button>
function clicked(){
console.log("Button was clicked REEEEe")}
The name of the function, click, is the issue. click is not a reserved word in JavaScript but the name does exist elsewhere in the scope where the onclick handler runs. You have 2 options:
Change the function name (doClick, for example).
Qualify the function name by referring to it as window.click in the onclick handler: onclick="window.click()"
There's a much more in-depth explanation here: javascript function name cannot set as click?
Unrelated to this, but something that could confuse someone during debugging: In your example code, your <div> is inside the <head> part of the HTML page. That content should actually be in the <body> section below, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="script.js"></script>
<meta charset="UTF-8">
<title>McKinsey Prep</title>
</head>
<body>
<div>
<button onclick="doClick()">Some Button</button>
</div>
</body>
</html>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I am very new to jQuery, literally just trying to get it to work for the first time. Only the alert box works, but none of the other very simple methods I am trying out. Here are the files:
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>jquery</title>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="myJavaScript.js"></script>
</head>
<body>
<h1 id="title">This is a title</h1>
<p> This is some sample text.</p>
</body>
</html>
JavaScript file:
$(document).ready(function (){alert("this works!")});
$("#title").text("but this is not not working");
As you can see the example can't be simpler. I have off course downloaded the jquery-3.1.0.min.js file and put it in the same folder as the html. If I comment out the link, the alert stops working, so I now the file is being referenced OK. Why is the second line of jQuery not working? Many thanks, P
Because the DOM(the entire structure of your application) isn't loaded yet. You need to use a $(document).ready(makes sure the DOM is loaded before running jQuery code) or an event handler to make the change visible.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
document.getElementById() doesn't work? [duplicate]
(7 answers)
Closed 7 years ago.
im new to javascript and want to fill a div with some text. but it doesn't work.
in the documentation this is the common way to do this. but, why doesn't work this for me?
my code is
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
document.getElementById('mytest').innerHTML="hey";
</script>
</head>
<body>
<div id="mytest"></div>
</body>
</html>
You need to move your script to the end of your HTML. Right now, you're executing the script BEFORE your HTML has been parsed so the document is empty and thus document.getElemntById('mytest') does not find anything.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="mytest"></div>
<script type="text/javascript">
document.getElementById('mytest').innerHTML="hey";
</script>
</body>
</html>
See this other answer for a lot more discussion of this issue and other options if you don't want to move your <script> tag:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
thats because, in your document, the javascript is load at the first, but the div with the id mytest is not loaded at this moment.
you have 2 options to get this working:
first: say javascript to wait until the dom is loaded completly
window.onload=function(){
document.getElementById('mytest').innerHTML="hey";
}
second:
put your script code at the bottom, so the javascript is loaded at least.
but i would prefer the first solution.
best
Try in this way
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="mytest"></div>
</body>
<script type="text/javascript">
document.getElementById('mytest').innerHTML="hey";
</script>
</html>
Js fiddle
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
I'm trying to get the element with getElementById(), but it returns null even though the element exists. What am I doing wrong?
<html>
<head>
<title>blah</title>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</head>
<body>
<div id="abc">
</div>
</body>
You have to put this in a document load event. The DOM hasn't gotten to abc by the time the script is executed.
Your script runs before the DOM has been loaded. To fix this you can place your code in the window.onload function like so:
window.onload = function() {
alert(document.getElementById("abc"));
};
An alternative is to place your script right before the closing </body> tag.
If you don't want to attach to the load event then simply put your script at the bottom of the body, so it will execute at the end-
<html>
<head>
<title>blah</title>
</head>
<body>
<div id="abc">
</div>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</body>
</html>
This is because the script runs before the page has rendered.
For proof add this attribute to the body tag:
<body onload="alert(document.getElementById('abc'));" >
But it doesn't exist, not at that point in the HTML. HTML documents are parsed top-to-bottom, just like programs run. The best solution is just to put your script tag at the bottom of the page. You could also attach your JavaScript to the onload event.
This question already has answers here:
when and where to put javascript in html
(7 answers)
Closed 9 years ago.
the thing is i'm unable to figure out where to embed javascript in html page whether in head section or body section.
example 1:
<html>
<head>
<title>events</title>
<script>
document.getElementById("b").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<p id="demo"></p>
<button id="b">new</button>
</body>
</html>
in the above example I placed script tags in head section but it is not working.
example: 2
<html>
<head>
<title>events</title>
<script>
function upper()
{
var x=document.getElementById("t");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body >
enter some text:<input type="text" id="t" onChange="upper()"/>
</body>
</html>
in the second example I placed the javascript in head section it is working properly.first example demonstrates that on clicking a button date will be displayed in the second example in a text box when data is entered and if we come out of the box the letters in the box will we converted to uppercase.
To have it more readable I prefer to always place JavaScript in the head section. If you need to access elements from there, use the window.onload event:
<head>
<title>events</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("b").onclick = function() {
displayDate();
};
};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
This would work just fine.
Your second example worked because you just defined a function, you didn't try to access any element.
You can put it in the head. The problem is that your examples are not the same. The first one doesn't work because the current date is retrieved by calling Date(), when it should be new Data().getDate(). The second example works because the code is valid.
The problem you're running into is that you're trying to reference an element before it is loaded into the DOM.
When you're putting the script in the HEAD tag, the dom hasn't been loaded yet and the document.getElementById won't find what you're looking for.
You have a few different options to deal with this. You can put the script at the end of the page, which will work for your small example here.
Probably a better option is to take a look at learning/using jquery or another js utility. Jquery makes it easy to solve this issue by giving you a "ready" event. This ready event will be triggered when the DOM is fully loaded. So:
$(document).ready(
function()
{
$("#demo").html((new Date()).toString());
});
Is all you really need. With this approach, it doesn't matter where the script it on the page.