.innerHTML problems storing it into a variable - javascript

Here is my code that is not working - thanks guys - first question!
<html>
<head>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
</script>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
Also sorry for the update but do you guys have an idea of how to do this when the div is in an iframe thats not on the same domain? Thanks

This line
var x = document.getElementById("myElementId").innerHTML;
is executed before the element with ID myElementId exists, so JavaScript cannot find it (getElementById returns null).
Put it after the element:
<div id="myElementId">24</div>
<script>
var x = document.getElementById("myElementId").innerHTML;
</script>
The HTML document is processed from top to bottom.

You're running this line:
var x =document.getElementById("myElementId").innerHTML;
before the element exists. Remove the script from the head an put that line right before:
if(x < 25) {
Instead.

In addition to the creating the element first,
I believe innerHtml returns a string value
Try parsing it first;
var value = document.getElementById("myElementId").innerHTML;
var x = parseInt(value,10)

change it to:
<html>
<head>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
the element that you are trying to look for does not even exist on the page when you run the script that is why you have run into this issue..

document.getElementById("myElementId").innerHTML;
You have to use a # with Id and . with class in it
document.getElementById("#myElementId").innerHTML;

Related

Can't figure out how to randomly generate numbers with a button in javascript

followed a tutorial just with different layout and names and still can't seem to find whats wrong?
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = math.floor((math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
Reason :
What you are doing wrong is that you are using math instead of Math. JavaScript is case sensitive and Math is defined while math is not.
Corrected :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
<script>
var myrandom = () => {
var x = ~~((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</body>
</html>
Also please note that it is better that you write the JS code at the end of the body tag and the script tag is the last one in the body tag.
Note :
Note that I edited the snippet provided by you.
The following edits were made
The script tag was moved at the end of body tag
I changed the function and used arrow syntax instead of normal declaration
Changed Math.floor into bitwise ~~
Resources :
Stack overflow script tag
W3 schools script tag
bit wise operators mozilla
bit wise operators W3 schools
Arrow function mozilla
You have a typo, You need to capitalize the first letter of math -> Math.
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>

Undefined when doing document.write() with button OnClick="counter"

I'm new to programming and would need some help, why the document.write() didn't work and basically the page crashes... Can anyone help me?
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
function showText() {
var x;
var counter;
if ( x === 0) {
counter = 0;
x = 1;
}
counter = counter + 1;
document.write("Times clicked: " + counter);
}
</script>
<body>
<script type="text/javascript">
showText();
</script>
<button onclick="showText();">Click Me!<button>
</body>
</html>
Avoid using document.write
Quoting from the MDN Developer Network documentation page:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So basically, your issue is using document.write after the page has loaded: this will result in deleting the entire content of the page and displaying that string.
Also, your code doesn't work because your count variable is declared inside the showText function, and you're trying to access it outside of it, running into an error.
Solution
To make your code work you should create another element, let's say a <p> element, and display the text inside of it. Here's an example of a correct page:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me!</button>
<p id="txt">Times clicked: 0</p>
<script type="text/javascript">
function showText() {
count++;
text.textContent = "Times clicked: " + count;
}
var count = 0,
button = document.getElementById("btn"),
text = document.getElementById("txt");
button.addEventListener("click", showText);
</script>
</body>
</html>
Check out a live demo here.

TypeError: getElementById is null

<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>

Support needed for looping my code

Can someone please help me how to loop my function ?
here is my code i just want that my will execute more times than only one.
I have already tried to create my own for loop, but it doesnt work.
Hope someone is so friendly to help me out with my problem and can give little bit explain about how to get rid of my problem with loops.
<html>
<head>
<script type="text/javascript">
for (var i = 1; i<=4; i++){
windows.open(i);
}
function MultiplyLinks(){
window.open("#")
window.open("#")
window.open("#")
}
</script>
<title>Javascript MultiplyLinks Opener</title>
</head>
<body>
<a h ref ="javascript:MultiplyLinks()">Open More links</a>
</body>
</html>
Well guys thanks . I 've got the problem.
i have used windows.open(i);
but it has to be MultiplyLinks(i);
otherwise it will never recognize my function.
i just wanted that my 3 links will executed more times and that works for now.
Thanks for all the replies.
Few issues:
1) you've got a typos
change
windows.open(i)
to
window.open(i)
2) Why are you trying to open i rather than use a url?
suggest you change i to something more meaningful like:
window.open('http://someusr');
3) you have a space in the anchor tag :
change
<a h ref=
to
<a href=
so the final code:
<html>
<head>
<script type="text/javascript">
for (var i = 1; i<=4; i++){
window.open('http://www.stackoverflow.com');
}
function MultiplyLinks(){
window.open("#")
window.open("#")
window.open("#")
}
</script>
<title>Javascript MultiplyLinks Opener</title>
</head>
<body>
Open More links
</body>
</html>
var links = [
'http://jquery.com',
'http://stackoverflow.com/',
'https://bitbucket.org',
'https://github.com'
];
for (var i = 0; i < links.length; i++){
window.open( links[i] );
}

HTML/JavaScript it won't let me append to a div

<html>
<head>
</head>
<body>
<div id = "start">
<h3>Start</h3>
<script>
if(Go==false)
document.write("<p>None </p>");
else
document.write("<p>Month: Day: Hour: Min: </p>");
</script>
</div>
<script>
var change = function(){
document.getElementById('start').innerHTML +=document.write("<p>NO</p>");
};
</script>
<input type = "button" value =start onClick = "change(); return false;"/>
<body>
</html>
With this it refreshes the page and I need it to be added to the div "start". Any Ideas? I have been looking up things online with fixes and none seem to work for me. I use chrome, I don't know if that will help.
Try this:
var change = function(){
document.getElementById('start').innerHTML += "<p>NO</p>";
};
This is a similar question of question on SO.
Is as to avoid of the use document.write("<p>NO</p>"); because this needs to refresh page.
Then I suggest for you use document.getElementById('start').innerHTML +="<p>NO</p>";
Or create the element!!
var p= document.createElement('P');
p.appendChild( document.createTextNode("NO") );
document.getElementById("start").appendChild(p);
Yup, what sjkm said. document.write does not return anything, it just appends whatever you give it to the end of the document. Also, your Go variable isn't declared and has no value assigned to it

Categories

Resources