Generate random fact from an array [duplicate] - javascript

This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 2 years ago.
I was trying to make a random fact generator website which would generate some random facts from an array, This is how I expected it to work - First I created a button which on click would generate a random fact but unfortunately The button is not working. Please check the code below and tell me the mistakes that I made.
Code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
<script>
var facts = ["I will add more facts later" , 'Heaven']
var randomFact = randomlist(facts);
function generateFacts(){
getElementById('here').innerHTML = randomFact;
}
function randomlist(list){
var x = Math.floor(Math.random() * list.length);
return list[x];
}
</script>
</body>
</html>

There is no function called getElementById alone. You need to use the method inside document object. So, the function will be document.getElementById()
var facts = ["I will add more facts later", 'Heaven']
var randomFact = randomlist(facts);
function generateFacts() {
document.getElementById('here').innerHTML = randomFact;
}
function randomlist(list) {
var x = Math.floor(Math.random() * list.length);
return list[x];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facts generator website</title>
</head>
<body>
<div id="container">
<button id="btn" onclick="generateFacts()">Click me!</button>
<div id="here">
</div>
</div>
</body>
</html>

How about document.getElementById()?
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}

If you open the developer console you should see the error that points out the mistake:
The function getElementById is not defined.
So the function generateFacts should look like this:
function generateFacts(){
document.getElementById('here').innerHTML = randomFact;
}
document is the owner of all the DOM elements of the page. So you should call it to help you find the element.

Related

How should I make input permanent and make the input stay even after reloading the page in html? [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 1 year ago.
How should I make input permanent? Like for example, if I type in "Hello world" it should say "hello world " and "hello world" should be there even after reloading
<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">
<title>Document</title>
</head>
<body>
<p id="content"></p>
<input type="text" id="userInput">
<script>
function getInputFromTextBox() {
let input = document.getElementById("userInput").value;
document.getElementById("content").innerHTML = input;
}
</script>
<button onclick="getInputFromTextBox()">submit</button>
</body>
</html>
You can use localStorage
// JAVASCRIPT
// Getting the value from localStorage
// The "key" here need to be the same defined below on the save() function
const getValue = localStorage.getItem("key");
if (getValue) {
document.getElementById("inputId").value = getValue;
}
function save() {
const setValue = document.getElementById("inputId").value;
// Here you can set 'key' with any name you like
// Setting the value in localStorage
localStorage.setItem("key", setValue);
}
<!-- HTML -->
<input type="text" id="inputId" />
<button onclick="save()">save value</button>
<!DOCTYPE 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">
<title>Document</title>
</head>
<body>
<h3>Type here</h3>
<input type="text" id="inputText">
<input type="submit" id="submit">
<p id="seeHere"></p>
</body>
<script>
if(localStorage.getItem("info")==null){
}
else{
value();
}
let submit = document.getElementById("submit");
submit.addEventListener("click", function () {
console.log("hello world");
let inputText = document.getElementById("inputText");
let inputTextvalue = inputText.value;
inputText.value="";
let localValue = localStorage.getItem("info");
if (localValue == null) {
arr = [];
}
else {
arr = JSON.parse(localValue);
}
arr.push(inputTextvalue);
localStorage.setItem("info", JSON.stringify(arr));
value();
})
function value() {
let localValue = localStorage.getItem("info");
let seeHere = document.getElementById("seeHere");
seeHere.innerHTML="";
let seeHeretext="";
let parsedLocalvalue= JSON.parse(localValue);
parsedLocalvalue.forEach(element => {
seeHeretext=seeHeretext+`${element}<br>`;
});
seeHere.innerHTML=seeHeretext;
}
</script>
</html>
This is the required answer for the question see carefully .

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"/>

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;
}

InnerHTML- fetching from script

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 />';

Document.getElementByClassName not working [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to use Document.getElementByClassName, but it isn't working. I've included my code below. I'd appreciate any help.
HTML document:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<style></style>
</head>
<body>
<h1 class=myclass> Some text</h1>
</body>
</html>
JavaScript code:
var change = document.getElementByClassName("myclass");
change.innerHTML = "New text";
It's getElementsByClassName Elements
Returns an array-like object of all child elements which have all of the given class names
- Mozilla Developer Network / Document.getElementsByClassName()
Loop through it or use change[0].innerHTML
1
var change = document.getElementsByClassName("myclass");
change[0].innerHTML = "New text";
<h1 class="myclass"> Some text</h1>
2
var change = document.getElementsByClassName("myclass");
for (var i = 0; i < change.length; i++) {
change[i].innerHTML = "New text";
}
<h1 class="myclass"> Some text</h1>
Right before the closing body tag (), you want to add a script tag to attach your JavaScript file into the HTML file, so that they're both linked.
This is how it should look:
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<style></style>
</head>
<body>
<h1 class=myclass> Some text</h1>
<script src="javascriptfile.js"></script>
</body>
Also, it's "getElementsByClassName"; elements is plural

Categories

Resources