Why won't this simple code run? [duplicate] - javascript

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.
<html>
<head>
</head>
<body>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
<p id='test'> </p>
</body>
</html>
Sorry, i'm not sure if i'm missing something, but how come this code isn't running? thank you in advance, sorry if this is a stupid question!

At the time of running var a = document.getElementById('test').innerHTML = toD(15); in your script <p id='test'> </p> does not exist.
place the script AFTER <p id='test'> </p> or wrap the entire script in its own function and assign it to onload so that it is only ran after <p id='test'> </p> and the rest of the DOM is available.
Either
<html>
<head>
</head>
<body>
<p id='test'> </p>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
OR
<html>
<head>
</head>
<body>
<script>
window.onload = function() {
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
}
</script>
<p id='test'> </p>
</body>
</html>
Note: this is a very dirty way of using window.onload, that should only be used if this is to be the only script on the page that requires onload. For more information about using onload properly when there will be multiple scripts using it, please read How to Use window.onload the Right Way

You need to wait until the document loads, as you're trying to access an element (#test) before the HTML has been fully parsed by the browser - you can use window.onload so that your JS is run after the document has been loaded - e.g.
window.onload =
// JS

Look at the JavaScript console [f12] and you will see an error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
The error occurs because you are referencing the element before it is rendered to the page.
Put the script tag after the element so it can find the element.
<html>
<head>
</head>
<body>
<p id='test'> </p>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>

Because when you run document.getElementById('test') the DOM object <p id='test'> </p> wasn't rendered yet.

Problem in rendering
Change your code as below :
<html>
<body>
<p id='test'> </p>
<script language="javascript">
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
-> Please read about how web page is parse. you will clear your idea about where to write script in your page.
->object should be rendered before performing operation on it. in your code div is not rendered and you try to perform operation on it ( i.e. document.getElementById('test').innerHTML = toD(15); )

Place the script at the bottom of the page to avoid problems like this noted above, also use windows.onload http://www.w3schools.com/jsref/event_onload.asp - to ensure the element is rendered before you cast on it.

Related

How can I make a variable be the select Id in a getElement

How can I make a variable be the select Id in a getElement? When I tried it, it returned null. My code is shown below:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body
</html>
That code seems to work just fine (with the exception of the unclosed body tag), here is a runnable version of the code, fixed:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body>
</html>
Remember, the js code is going to happen almost immediately, so you won't be able to see the "hi" part. If you want it to change after like 1 second, use this:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
setTimeout(function () {
document.getElementById(test).innerHTML = "complete";
}, 1000);
</script>
</body>
</html>
All I changed in that, is put the document.getElementById() into a setTimeout
Hope this helped.

Printing object property in an html paragraph

I should get an output of "Peter" in the paragraph with id="para1", but somehow, this is not happening. Can someone help me out?
<html>
<head>
</head>
<body>
<p id=para1></p>
<script>document.getElementById('para1').innerHtml = alpha.name;</script>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
</script>
</body>
</html>
I've changed the code to this, still cannot see the word "Peter" in the html screen:
<html>
<head></head>
<body>
<p id=para1></p>
<script>
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHtml = alpha.name;
</script>
</body>
</html>
There are two mistake you have.
First: <p id=para1></p> id must have " like <p id="para1"></p>
Second: innerHTML not innerHtml
Check your updated code here:
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
<p id="para1"></p>
Your main mistake is innerHtml instead innerHTML. But all your code is not good formatted.
Let's change your code
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
You're trying to call the object before it exists. Either change your script around, or use window.onload:
<script type="text/javascript">
window.onload = function(){
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
};
</script>
This makes sure that the page is fully loaded before the scripts gets executed.
This is by far the best and safest solution, but if you rather leave it to "load as you go", then changing the order would (perhaps) be sufficient:
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
Edit:
Also, as others mentioned - it's .innerHTML. Javascript is case sensitive.
<html>
<body>
<p id="para1"></p>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
</body>
</html>

How to get JavaScript text to show?

This is for a class I'm taking. Its homework out of the book for a particular chapter. The book provides some code that is purposly not working and you have to fix it. I've got it all working exept for this part where youre supposed to get some text to show up at the bottom of the screen that displays the last time the document was modified.
Ive gone over it repeatably and cant find whats wrong. Im wondering if the book has it wrong.
<head>
<script type="text/javascript">
function CopyRight() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
xxx.innerHTML = "<p style='font-size:8pt;'>The URL of this document is "+document.URL+"<br />Copyright Frank's Fix-t Hardware. This document was last modified "+lastModDate+".</p>"
</script>
</head>
<body>
<div id="xxx"></div>
</body>
The mistakes are in your program
Missing closing curly } brace.
Not invoking the function CopyRight()
Inside CopyRight() not getting the xxx element to work on this.
Script should be invoked when the dom is ready (so placed script after xxx tag)
Correct version of your program is
<html>
<head>
</head>
<body>
<div id="xxx"></div>
<script type="text/javascript">
function CopyRight() {
var xxx = document.getElementById('xxx'); //mistake 3
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
xxx.innerHTML = "<p style='font-size:8pt;'>The URL of this document is "+document.URL+"<br />Copyright Frank's Fix-t Hardware. This document was last modified "+lastModDate+".</p>"
} //mistake 1
CopyRight(); //mistake 2
</script>
</body>
</html>
This is the working one. The code works fine but you forgot to call the CopyRight function.
<head>
<script type="text/javascript">
function CopyRight() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
xxx.innerHTML = "<p style='font-size:8pt;'>The URL of this document is "+document.URL+"<br />Copyright Frank's Fix-t Hardware. This document was last modified "+lastModDate+".</p>"
}
CopyRight(); // Call Copyright function
</script>
</head>
<body>
<div id="xxx"></div>
</body>

not able to load contents in div using javascript

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>

Use javascript substring to specify character length

I have a heading on my webpage that I want to limit to a certain number of characters. The
heading is for a blog post so the title changes. This is essentialy what I want to accomplish.
<body>
<script>
var x= document.getElementById("entry-title");
document.write(x.substring(0,10));
<script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
try that
<body>
<script>
window.onload =
function (){
var x= document.getElementById("entry-title");
x.innerText = x.innerText.substring(0,10);
}
</script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
There the code with jquery
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" ></script>
</head>
<body>
<script>
$(document).ready(
function (){
var text = $("#entry-title").text();
var x= $("#entry-title").text(text.substring(0,10));
}
);
</script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
</html>
<h1 id="entry-title">This is a sample blog title</h1>
<script>
(function() {
var el = document.getElementById("entry-title"),
supportedProp = el.textContent != null ? 'textContent' : 'innerText';
el[supportedProp] = el[supportedProp].substring(0, 10);
}());
</script>
Demo
You have to either place your script below the element that you want to reference or defer its execution with a DOMContentLoaded or window load event handler.
Also, the W3C standard property is textContent instead of IE's proprietary (and adopted by Chrome) innerText property. Therefore you need to do some feature detection if you want to support both Firefox and IE. Chrome accepts either of the properties.

Categories