Cannot read property 'setAttribute' of null - Javascript - javascript

I have seen a couple of questions posted with this error on here and having seen some of the answers I noticed the general consensus is that it is caused due to the DOM not being created yet. I have tried a few different solutions to fix it such as moving my script to immediately prior to the tag, using log outputs before and after the image creation in order to ensure the object is actually being created correctly but nothing has resolved my issue. I am new to Javascript so it might be something obvious I am missing?
var dice = [6, 6, 6, 6, 6];
function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>
<head>
<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>

Since you're using document.write after the document has loaded, it's clearing the entire document (due to document.open() being called). Therefore, your img elements do not exist for setAttribute to be run against them. Try the following (note the index corrections that are needed due to array indexing starting at zero):
var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');
function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}

Related

JavaScript onclick why does it say function not defined?

I have been writing this code to generate a countdown maths question and answer, but it doesn't work when i run it (sorry for questionable variable names also this is one of my first times using JavaScript so i might not be doing sone things right):
function remove(arr, value){
for( var i = 0; i < arr.length; i++){
if ( arr[i] === value) {
arr.splice(i, 1);
}
}
}
function pop(array, value){
let n = array[value]
remove(array, value)
return n;
}
let num = [25, 50, 75, 100]
let anum = []
function genrt(){
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
for(i=0; i<leng; i++){
anum.push(Math.floor(Math.random()*10)+1)
}
for(i=0; i<small; i++){
anum.push(num[Math.floor(Math.random()*3)])
}
document.getElementById("1").innerHTML = "Your numbers are: " + String(anum);
let nuum = Math.floor(Math.random()*(anum.length-1))
let out = anum[nuum]
remove(anum, nuum)
ans = String(out)
lenggg = Math.floor(Math.random()*anum.length-3)+3
for(i=0; i<lenggg; i++){
let op = Math.floor(Math.random()*3)
let nnuu = Math.floor(Math.random()*(anum.length-1))
let nuuuum = anum[nnuu]
remove(anum, nnuu)
if(op==0){
out+=nuuuum
ans+='+'
}
if(op==1){
out-=nuuuum
ans+='-'
}
if(op==2){
out*=nuuuum
ans+='*'
}
if(op==3){
out/=nuuuum
ans+='/'
}
ans+=String(nuuuum)
ans+='\n'
}
document.getElementById("2").innerHTML = "Your target is: " + String(out);
}
function reveal(){
document.getElementById("3").innerHTML = "The solution is (without bodmas): " + ans;
}
<!doctype html>
<html>
<head>
<title>countdown generator</title>
</head>
<body>
<p>How many small numbers</p>
<input type="int" id="i1" value=3>
<p>How many big numbers</p>
<input type="int" id="i2" value=2>
<button onclick="genrt()">Generate</button>
<p id="1">Your numbers are:</p>
<p id="2">Your target is:</p>
<button onclick="reveal()">Solve it</button>
<p id="3">The solution is (without bodmas)</p>
</body>
</html>
But when i press the generate button it says function genrt not defined. I have looked for an answer for ages and tried quite a few things but nothing seems to work, does anyone know what i am doing wrong?
You have syntax errors on these lines:
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
You have misplaced ; symbol. You should always read console output, the error was clearly visible in the console logs.
Your script has a syntax error. The first error you should be seeing in your console is
Uncaught SyntaxError: missing ) after argument list
Obviously, since it failed to compile the Javascript, then when you afterwards try to call a function from that failed block, it will not exist because the JS engine couldn't read the code in order to load it.
If you fix the syntax error then the undefined function error will go away. It's actually a fairly simple couple of typos:
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
needs to become
let leng = parseInt(document.getElementById("i1"));
let small = parseInt(document.getElementById("i2"));
; is always to end a line - if you have something after the ; which doesn't of itself form a valid line of code, then you know it's definitely wrong. I suggest using an IDE or code editor which understands JavaScript syntax and can highlight these kinds of issues to you before you even attempt to run the code.
(I make no guarantees that you won't then have other unrelated errors or bugs, I haven't tested the code to that extent.)
there wqs semicolon in on those lines
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
ans variable was not difine
but i dont know if the result is what you want
i have make some corrections
<html>
<head>
<title>countdown generator</title>
</head>
<body>
<script>
function remove(arr, value){
for( var i = 0; i < arr.length; i++){
if ( arr[i] === value) {
arr.splice(i, 1);
}
}
}
function pop(array, value){
let n = array[value]
remove(array, value)
return n;
}
let num = [25, 50, 75, 100]
let anum = []
let ans = null
function genrt(){
let leng = parseInt(document.getElementById("i1"))
let small = parseInt(document.getElementById("i2"))
for(i=0; i<leng; i++){
anum.push(Math.floor(Math.random()*10)+1)
}
for(i=0; i<small; i++){
anum.push(num[Math.floor(Math.random()*3)])
}
document.getElementById("1").innerHTML = "Your numbers are: " + String(anum);
let nuum = Math.floor(Math.random()*(anum.length-1))
let out = anum[nuum]
remove(anum, nuum)
console.log(String(out))
ans = String(out)
lenggg = Math.floor(Math.random()*anum.length-3)+3
for(i=0; i<lenggg; i++){
let op = Math.floor(Math.random()*3)
let nnuu = Math.floor(Math.random()*(anum.length-1))
let nuuuum = anum[nnuu]
remove(anum, nnuu)
if(op==0){
out+=nuuuum
ans+='+'
}
if(op==1){
out-=nuuuum
ans+='-'
}
if(op==2){
out*=nuuuum
ans+='*'
}
if(op==3){
out/=nuuuum
ans+='/'
}
ans+=String(nuuuum)
ans+='\n'
}
document.getElementById("2").innerHTML = "Your target is: " + String(out);
}
function reveal(){
document.getElementById("3").innerHTML = "The solution is (without bodmas): " + ans;
}
</script>
<p>How many small numbers</p>
<input type="int" id="i1" value=3>
<p>How many big numbers</p>
<input type="int" id="i2" value=2>
<button onclick="genrt()">Generate</button>
<p id="1">Your numbers are:</p>
<p id="2">Your target is:</p>
<button onclick="reveal()">Solve it</button>
<p id="3">The solution is (without bodmas)</p>
</body>
</html>

Unknown error writing an array to an element in javascript?

I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
<script>
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementsByClassName('boxed').innerHTML = numList;
</script>
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div class="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>
your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div>
When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
console.log(numList)
};
numList.toString();
document.getElementById('boxed').innerHTML = numList;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>

How to compare the current variable with current type?

In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.
Output number
Input string
Output string
HTML
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" id="myText">
Submit
<br/>
<br/>
<label for="myText2">Input for delete:</label>
<input type="text" id="myText2">
Submit
</body>
</head>
</html>
Javascript
window.onload = function(){
inputBox =document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
saveArr(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});
function saveArr(arr) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function removeItemAndprintNewArray(rv, number) {
var tmp = [],
st = "";
for(var index in rv){
if(rv[index] !== number){
tmp.push(rv[index]);
}
}
for (var i = 0; i < tmp.length; i++){
if (typeof(tmp[i]) == "String"){
st += tmp[i];
console.log(st);
}
else if (typeof(tmp[i]) === "Number"){
st += tmp[i];
console.log(st[i]);
}
}
}
}
Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)
Small example
var arr = [12, "asd", 4];
arr.forEach(function(item) {
console.log(item - 0);
});
So you can check on NaN, don't forget that you should use special function isNaN()
var arr = [12, "asd", 4];
arr.forEach(function(item) {
if(isNaN(item - 0)) {
//do what you want with string
console.log("string");
};
else {
//do what you want with Number
console.log("number");
}
});

Need Assistance With JavaScript ImageSlider - What Am I Doing Wrong?

<script type="text/javascript">
var imageCounter = 1;
Function change() {
var image = doc.getElementById("image2");
if( imageCounter==1 ) {
image.src = '2.jpg';
imageNumber = 2;
}
else if( imageCounter==2 {
image.src = '3.jpg';
imageNumber = 3;
} else {
imageCounter = 1;
}
setInterval("change()",6500);
<button id="knapp1" type="button" onclick="change()">==></button>
Can anyone tell me what I am doing wrong? I have been trying to understand what I'm failing.
The main problem is that sometimes you assign to imageCounter and sometimes you assign to imageNumber. Decide on one name and use it consistently.
Also, function does not start with a capital letter. JavaScript is case-sensitive.
One problem is that you have
Function change()
with a capital F.
It should be function change()
another thing is that imageNumber is not declared. Im not sure what it is or what its used for but just do
var imageNumber;
setInterval("function()",6000);
It should not be in quotes.
setInterval(change(),6000);
Next thing, is that if you are running this off your computer, it will not find 3.jpg
Instead you have to give the complete file location of the image.
One last thing: on your function you are missing a curly bracket at the end.
heii
copy this code
<html>
<head>
<link rel="stylesheet" type="text/css" href="boss.css">
<script language="JavaScript">
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "1.jpg";
path[1] = "2.jpg";
path[2] = "3.jpg";
function change()
{
document.slide.src = path[i];
if(i < path.length - 1) i++; else i = 0;
setTimeout("swapImage()",6500);
}
window.onload=change;
</script>
</head>
<body>
<center>
<img src="1.jpg" border="1" name="slide" height="300" width="750" id="image2"/>
</center>
<button id="knapp1" type="button" onclick="change()">==></button>
</body>
</html>

Javascript 4-image slideshow w/ arrays & setTimeout

<script type=text/javascript>
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
for(var i = 0, l = topLeftImages.length; i < l; i++)
{
setTimeout(function()
{
document.getElementById('myimage1').src = "images\\" + "op.jpg";
document.getElementById('myimage2').src = "images\\" + topRightImages[i];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[i];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[i];
}, 10000);
}
</script>
Associated HTML:
<img id="myimage1" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage2" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage3" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage4" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
This code is meant to show four images, and every 10 seconds, switch all four images simultaneously, going through all of my images in my four arrays. The images are in the images/ directory above my HTML file that contains this code. For testing purposes, I changed myimage1 to change to op.jpg only. This works and correctly shows op.jpg. However, when querying the arrays, instead of the file names, I get undefined. That is problem number one.
Problem number two, when I change my for loop to a more normal looking one like:
for(var i = 0; i < l2; i++)
The script stops working entirely (doesn't show op.jpg and doesn't even try to change the images)... what the hell!
I'm using Firefox and Google Chrome for testing purposes.
I suggest something like that instead:
<script type=text/javascript>
$(document).ready(function () {
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
var i = 0;
var max = 12;
setInterval(function()
{
var index = i % max;
document.getElementById('myimage1').src = "images\\" + topLeftImages[index];
document.getElementById('myimage2').src = "images\\" + topRightImages[index];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[index];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[index];
i++;
}, 10000);
});
</script>
jsFiddle with some example images http://jsfiddle.net/ApfJz/8/

Categories