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

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

Related

How can I change the content from a paragraph tag in HTML by JavaScript if/else statement?

How can I change the content of the paragraph tag from HTML by JavaScript without using document.write? Why is it not showing when I view it in a browser? please help me learn this. Thanks
var grades = [45, 32, 66];
var sum = 0;
if (grades.length>0){
for (index=0 ; index<grades.length; index++)
sum += grades[index];
console.log(sum);
document.getElementById('here').innerHTML = sum/grades.length;
}
else
document.getElementById('here').innerHTML = "Empty Array";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array average with zero</title>
<script src="js/arrays2.js"></script>
</head>
<body>
<p id="here">See Average Here</p>
</body>
</html>

In my Project (Random quote generator). I am unable to sort issue?

I am making Random quote machine project using vanilla javaScript. I am doing this project using fetch-api(quotable.io) and simple Dom manipulation. My code is correct but there is some issues that I am unable to identify.
My Code is:
<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="Random.css">
<title>Random Quotes Machines</title>
</head>
<body>
<h1>Random Quotes </h1>
<br> <br>
<div class="container">
<p class="p">undefined </p>
<h6 class="author"> undefined</h6>
</div>
<button class="NextQuote" onclick="NextQuote()">NextQuote</button>
<!-- <button class="previous">Previous</button> -->
<script>
let container = document.getElementsByClassName("container");
let p = document.querySelector(".p");
let author = document.querySelector(".author");
let rem;
function NextQuote (){
rem = Math.floor(Math.random()*100);
fetch('https://api.quotable.io/random')
.then(response => response.json())
.then(quotes => {
p.innerHtml = '"${quotes.content}"';
}
);
}
</script>
</body>
</html>
You need to change innerHtml to innerHTML.
And you need to change '"${quotes.content}"' to quotes.content.
The result would be:
fetch('https://api.quotable.io/random')
.then(response => response.json())
.then(quotes => {
p.innerHTML = quotes.content;
}
);
Your sample almost works. There are only some small issues in your code:
quotes.content contains a plain text, to add the text to the paragraph you could use p.textContent instead.
you are using simple quotes instead of backticks for the template string, so your variable quotes.content wouldn't be interpolated.
To make it work replace the line p.innerHtml = '"${quotes.content}"'; with p.textContent = `"${quotes.content}"`;

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 .

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>

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

Categories

Resources