InnerHTML- fetching from script - javascript

I am trying to display random numbers from 1 to 7. I do not want them to repeat and I want to display every number. I've written my JS code inside script tag. I want to get a random number whenever button is clicked, instead I'm getting error
Uncaught TypeError: Cannot set property 'innerHTML' of null
at grandom (fe.html:48)
at HTMLButtonElement.onclick (fe.html:25)
Below is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Goplan Project Selection</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.1/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<div class="text-center">
<img src="cissoiree.jpg" width="80px" height="80px">
<h1 style="text-size:300em">Go-Plan</h1></div></div>
<div style="padding-top:20px;" class="text-center">
<button class="btn-lg btn-primary" onclick="grandom()">Click!</button>
<p id="demo"><p>
</div>
<script type="text/javascript">
function grandom()
{
var q=[2,3,1,5,4,7,6];
var x=7;
var i;
x=q.length;
var random;
while(1)
{
random = Math.floor(Math.random()*x);
if(random<=q.length)
break;
}
document.write("<br>");
document.write("Question No : " + q[random] );
if(q.length!=1)
<!--document.write("<input type=button value=click here onclick=grandom();><br>");-->
document.getElementById("demo").innerHTML = q[random];
q.splice(random,1);
document.write("<br>");
}
</script>
</body>
</html>

After document.write(...); there is no other elements in the page expect the passed text.
It is why when you trying to find then document.getElementById("demo") it's cannot find, and return null. (then throw error, when you trying to access its innerHTML)
If you trying to append something to the page you should use document.body.innerHTML += "...".
About the algorithm itself - you can use:
[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});
It will shuffle the array randomly.

Your document.write(..) is breaking it.
You can try:
document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';

Related

Clever Programmer Javascript tutorial Age in Days Challenge

For the age in Days challenge in this video, I'm getting the following error:
Uncaught TypeError: Cannot read properties of null (reading 'appendChild') at yearBorn (script.js:10:47) at HTMLButtonElement.onclick (challenge.html:19:64) yearBorn # script.js:10 onclick # challenge.html:19
JS:
function yearBorn() {
var birthYear = prompt('What year were you born?');
var ageInDays = (2022 - birthYear) \* 365;
var h1 = document.createElement('h1');
var textAnswer = document.createTextNode('You are ' + ageInDays + ' days old');
h1.setAttribute('id', 'yearBorn');
h1.appendChild(textAnswer);
document.getElementById('flex-box-result').appendChild(h1);
html:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<title>Javascript Challenge</title>
<link rel="stylesheet" href="static/css/index.css"
</head>
<body>
<div class="container-1">
<h2>Challenge 1: Your Age in Days</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick="yearBorn()">Click Me</button>
</div>
<div>
<button class="btn btn-danger">Reset</button>
</div>
</div>
<div class="flex-box-container-1">
<div class="flex-box-result"></div>
</div>
</div>
<script src="static/js/script.js"></script>
</body>
</html>
Why am I getting the error?
I was expecting the age in days to print to the flex box container below the buttons in the document. Instead, getting the error
Solution 1
The error in this line
document.getElementById('flex-box-result').appendChild(h1)
Because document.getElementById() need an id which you provide when creating html element like this
<div id="id"></div>
Your flex-box-result is a class
<div class="flex-box-result"></div>
to
<div class="flex-box-result"></div>
Solution 2
In JavaScript code, you can also use a querySelector method with the selector of your element (like CSS selector)
document.querySelector('.flex-box-result').appendChild(h1)

Uncaught TypeError: Cannot read property 'addEventListener' of null when i run got this error

i tried this code but when i run the code this problem exist
Uncaught TypeError: Cannot read property 'addEventListener' of null when i run got this error
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="btns" type="submit" placeholder="submittt" />
<script src="index.js"></script>
</body>
</html>
and in index.js
var l = document.querySelector("btns");
l.addEventListener("click", myfunction);
myfunction();
{
var k = Math.floor(Math.random() * 10);
alert(k);
};
Just call the function inside the eventlistener function:
You need to use the . to get element which has class.
var l = document.querySelector(".btns")
l.addEventListener("click", function() {
alert();
});
function alert(){
var k = Math.floor(Math.random() * 10);
alert(k);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="btns" type="submit" placeholder="submittt" />
<script src="index.js"></script>
</body>
</html>
You need to use the . in your class name when using querySelector.
Update the line to var l = document.querySelector(".btns");
Also, you will need to change myfunction(); to function myfunction()
Have a look at the definition of querySelector at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
querySelector uses CSS selectors so by asking it to find the first element with selector 'btns' you are asking it to find the first element with tag btns in the DOM. It can't find one so returns null.
To get it to find the first element with class="btns" you need to use the same syntax as you would in the CSS stylesheet: '.btns'
There was 2 issue in your code
The querySelector parameter was not correct
The click handler not properly written
Please find below code which depicts what you trying to achieve.
const l = document.querySelector(".btns");
l.addEventListener("click", myfunction);
function myfunction() {
var k = Math.floor(Math.random() * 10);
alert(k);
};
<input class="btns" type="submit" placeholder="submittt" value="submit"/>

Passing and getting an array displayed as html text

I'm passing an array of strings to be displayed as html text inside a
my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"]
which is displayed as :
PRODUCT, SHAMPOO1, SHAMPOO2, SHAMPOO3, SHAMPOO1.
What I want to do is make these clickable. And when I click on one of these words I want that word to be displayed below it.
What's the cleanest way to do this?
Passing the array in the <a> tag isn't working for me.
you can add it to the DOM, then loop your array to the li under ul
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<div id="products"></div>
<body>
<script>
var my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"];
var str = "<ul>";
my_arr.forEach(function (product) {
str += "<li> <a href='/'>" + product + "</a> </li>";
});
str += "</ul>";
document.getElementById("products").innerHTML = str;
</script>
</body>
</html>

Javascript. Why won't my string replace update show in my browser

I am trying to change the word "lion" to "monkey" by using a function by using .replace in Javascript. I have set a time interval on it and it does work, but only in the console. Not in the browser when I am viewing the page. Why? Do I need to assign/update/upload it to the HTML somehow?
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
}
setInterval(toggleCaps, 3000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="about">
<blockquote>
<p>
lion
</p>
</blockquote>
</div>
</body>
</html>
You need to update the html element with the replaced string as following:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
document.querySelector(".about").innerText = sum; //add this
console.log(sum);
}
setInterval(toggleCaps, 3000);
yes you need to update the html:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
document.querySelector(".about").innerText = sum;
}

How to create a button on the second page?

<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints()
{
var points=prompt("How many points have you earned?");
document.write("<p>Buy your items now and prepare for battle! Choose wisely.<p>" );
document.write("<p><img src = 'sword.jpg'/><p>");
document.write("<p><img src = 'Waterskin.jpg' /><p>");
document.write("<p><img src = 'charm.jpg' /><p>");
document.write("<p><img src = 'Phone.jpg' /><p>");
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
<div>
<input type="button" onclick="buyStuffWithPoints()" value="Buy Sword(2500)!" />
</div>
</body>
</html>
So currently what happens is when I run it, it prompts me to enter amount of points, then it shows two buttons, "Start!" and "Buy Sword(2500)!". Then after clicking start, the next page shows 4 pictures of the items to buy.
What I want to happen is, after I enter the amount of points, I only want it to show the "Start!" button. Then on the NEXT page, the same page where the pictures show up, I want to show the "Buy Sword" button.
I understand why it's doing this, I just have no idea how to change it. Can anyone help me with this?
You must close your p tags and you should avoid document.write
<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints() {
var points = prompt("How many points have you earned?");
var html = "<p>Buy your items now and prepare for battle! Choose wisely.</p>"
+ "<p><img src = 'sword.jpg'/></p>"
+ "<div><input type=\"button\" onclick=\"buyStuffWithPoints()\" value=\"Buy Sword(2500)!\" /></div>"
+ "<p><img src = 'Waterskin.jpg' /></p>"
+ "<p><img src = 'charm.jpg' /></p>"
+ "<p><img src = 'Phone.jpg' /></p>"
document.body.innerHTML = html;
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
</body>
</html>

Categories

Resources