Why is document.getElementById() not working? - javascript

I want to make a program which adds a textbox every time you click a button. Here's my code:
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="linelist"></div><br />
<button id="addline" onclick="Addline();">+</button>
</body>
</html>
When I run it, it generates an error. Why is this occurring?

You have to define linelist outside the functions first with let or var:
let linelist = null;
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button
class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}

Related

Javascript how to change page title with user input

The thing i wanna do is when user writes something to input and sumbits it, the page will change to the input.
Example:
If user writes "Web" to the input, the page title should change to "Web"
Here's the code:
JS:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").textContent;
document.getElementById("title").innerHTML = newTitle;
}
HTML:
<!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 id="title">Web Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center><label id="originLabel">Welcome to Web Editor!</label><br></center>
<br><label id="changeTitleLabel">Change the title of Web: </label><br>
<input type="text" id="newTitle"><br>
<button type="button" id="titleSumbitBtn">Change</button>
</body>
</html>
You can assign new title to the document like this:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
This is actual implementation but keep in mind that it must run after the DOM element with id newTitle.
If you put your <script> tag inside <head>, you'll need DOMContentLoaded:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
})
try this:
document.getElementById("titleSumbitBtn").addEventListener("click", function (){
var newTitle = document.getElementById("newTitle").value;
document.getElementById("title").innerText = newTitle;
})

Why does this js code only change the last div?

The button should replace all the letters (a, b, c) with 'test', but it only replaces the last (c).
If I replace the line of code inside of updateHTML() with the commented line, the code works as intended. Can someone explain what the difference is and why the lines of code work differently.
My js and html files:
let names = ["a", "b", "c"];
let objs = [];
let container;
let form;
class Class {
constructor(name) {
this.name = name;
this.buildHTML();
}
buildHTML() {
container.innerHTML += `
<div id="${this.name}">
${this.name}
</div>`
this.inner_container = document.getElementById(this.name);
}
updateHTML() {
this.inner_container.innerHTML = "test";
// document.getElementById(this.name).innerHTML = "test";
}
}
function main() {
container = document.getElementById("container");
for (var name in names) {
objs.push(new Class(names[name]));
}
form = document.getElementById("form");
form.addEventListener('submit', eventHandler_submit_form);
}
function eventHandler_submit_form(event) {
event.preventDefault();
for (var obj in objs) {
objs[obj].updateHTML();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sample Text</title>
</head>
<body onload="main()">
<form id="form">
<button type="submit">Submit</button>
</form>
<div id="container"></div>
</body>
</html>

h1 element text is not changing using javascript but changes in console

I'm learning web development and I'm trying to do the simplest things in javascript to learn how it works. I have this problem, the h1 text is not changing on the page but when I open the console it prints the changed value each time , here's the code (Hint, the sleep() function is from the internet and I don't know anything yet about it but it works):
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
let counter = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function change(){
while(true)
{
document.querySelector("#show").innerText = counter;
counter++
console.log(document.querySelector("#show").innerText);
sleep(1000);
}
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
function change() {
let counter = 0;
setInterval(() => {
document.querySelector("#show").innerText = counter;
counter++;
}, 1000);
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
try changing your change function using setInterval. you can find how to use set interval using https://www.w3schools.com/jsref/met_win_setinterval.asp

Trying to create a random word game that will output a function with a click of an html button

I'm trying to create a word game that will choose a random item from a list but some of the items have different weights so they show up less often. I want the function to be called once the user presses a HTML button. I have the code working fairly well right now (to the console). My question is how can I get the output from the function into the html web page. If anyone could help me with this, it would be a huge help.
Here's my code:
var item = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
function testGame(input) {
var array = [];
for(var item in input) {
if(input.hasOwnProperty(item) ) {
for(var i=0; i<input[item]; i++ ) {
array.push(item);
}
}
}
return array[Math.floor(Math.random() * array.length)];
}
console.log(testGame(item));
I have some HTML code too, just don't know where or how to write the button code properly to produce the outcome I'm looking for.
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<script src="index.js"></script>
<button onclick="testGame();">Test</button>
</body>
</html>
You can make new function where you can call it on button just like you called it with console.log:
<button onclick="start();">Test</button>
and call your randomizing function inside:
function start() {
testGame(item)
}
Then inside function testGame don't use return, just save random word result in variable and print it in HTML:
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
I have added div result in HTML:
<div id="result"></div>
EXAMPLE SNIPPET:
var item = {
'apple': 10,
'banana': 10,
'orange': 10,
'grapes': 1,
}
function testGame(input) {
var array = [];
for (var item in input) {
if (input.hasOwnProperty(item)) {
for (var i = 0; i < input[item]; i++) {
array.push(item);
}
}
}
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
}
function start() {
testGame(item)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<div id="result"></div>
<script src="index.js"></script>
<button onclick="start();">Test</button>
</body>
</html>
Use getElementById to get an element by id, for this I gave your button an id. With addEventListener you can add an event (here: click) to be call a function.
Doing here your randomizing. Get the element where you want the output again with getElementByIdand add with textContent your answer to it.
const ITEMS = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
document.getElementById('btn').addEventListener('click', function testGame() {
var array = [];
for(var item in ITEMS) {
if(ITEMS.hasOwnProperty(item) ) {
for(var i=0; i<ITEMS[item]; i++ ) {
array.push(item);
}
}
}
document.getElementById('item').textContent = array[Math.floor(Math.random() * array.length)];
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<button id='btn'>Test</button>
<div id='item'></div>
</body>
</html>

Template literals are not interpolating variables

Just noticed today that template literals with html tags don't work, or maybe I wrote it wrong?
I tried to include p tags in the template literals (which I commented out in the snippet), but it didn't work. Does anyone have any ideas? Thanks!
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
//content += '`<p>${i.name} is a ${i.species}.</p>`'; <--this one doesn't work
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.
You need to change this:
'`<p>${i.name} is a ${i.species}.</p>`'
to this:
`<p>${i.name} is a ${i.species}.</p>`
The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.
See the following working example:
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
// content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
content += `<p>${i.name} is a ${i.species}.</p>`;
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Read more about template literals in the documentation.

Categories

Resources