Clever Programmer Javascript tutorial Age in Days Challenge - javascript

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)

Related

What could be wrong with my keypress event?

I'm trying to make a weather app, and use the API from openweathermap, I copied the baseurl from the web like this but it's not currently working...
const api = {
key:"03173bc8739f7fca249ae8d681b68955"
baseurl:"https://home.openweathermap.org/api_keys"
}
const searchbox=document.querySelector('.search-box');
searchbox.addEventListener('keypress', setQuery)
function setQuery(evt){
if (evt.keyCode==13)
//getResults(searchbox.value)
console.log(searchbox.value)
}
So when I type in the search box, the console doesn't show anything...
This is my html file:
<!DOCTYPE html>
<html>
<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> </title>
<link rel="stylesheet" href="weather.css">
</head>
<body>
<div class="app-wrap">
<header>
<input type="text" autocomplete="off" class="search-box" placeholder="Search for a city...">
</header>
<main>
<section class="location">
<div class="city">HCM City, Viet Nam</div>
<div class="date">Friday 25 June 2021</div>
</section>
<div class="current">
<div class="tempt">15<span>°C</span></div>
<div class="weather">Sunny</div>
<div class="high-low">13°C / 16°C</div>
</div>
</main>
</div>
<script src="weather.js"></script>
</body>
</html>
Is there something wrong with the baseurl or something, can anybody tell me?
wrap the selector with " ";
const searchbox = document.querySelector(".search-box");
also correct your api obj:
const api = {
key: "03173bc8739f7fca249ae8d681b68955",
baseurl: "https://home.openweathermap.org/api_keys"
}
You missed to add single quote in querySelector.
const searchbox=document.querySelector('.search-box'); // Corrected
also you need to update the API object
const api = {
key:"03173bc8739f7fca249ae8d681b68955",
baseurl:"https://home.openweathermap.org/api_keys"
}

I want to delete all checked lists pressing the delete button but I don't know how

I'm learning Javascript and now I'm making to-do list.I've finished the basic one but I want to add the delete button which delete all the checked lists to my to-do list.
I've tried some ways that I came up with and they all failed and I cannot find the answer by googling.
How can I do this ? If there is someone who know, please teach me . I'd appreciated if you could show me how.
this is my code ↓ the error happened saying cannot read property 'parentElement' of null at Object.deleteAll
deleteAll: function() {
let taskListItem, checkBox, checkBoxParent;
for (i=0; i<this.taskListChildren.length; i++){
taskListItem = this.taskListChildren[i];
checkBox = taskListItem.querySelector('input[type = "checkbox"]:checked');
checkBoxParent = checkBox.parentElement;
checkBoxParent.remove();
}
document.getElementById('deleteChecked').addEventListener('click', () => {
tasker.deleteAll();
});
🙏
// this is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="css/styles.css">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
<body onLoad = "tasker.construct();">
<div class="tasker" id="tasker">
<div class="error" id="error">Please enter a task</div>
<div class="tasker-header" id="tasker-header">
<input type="text" id="input-task" placeholder ="Enter a task">
<button id="add-task-btn"><i class="fas fa-plus"></i></button>
</div>
<div class="tasker-body">
<ul id="tasks">
</ul>
</div>
<button id="deleteChecked">Delete</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
You can use the jQuery library and solve it as follows.
Step 1) Define in your html button element:
<button id="button" onclick="reset()"> RESET </button>
Step 2) define the 'reset ()' function, like this
function reset()
{
$("input:chceckbox").removeAttr("chcecked");
}
Good luck!!

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

Element.insertAdjacentHTML() API throws error in chrome 55.0.2883.87

I found the explaination about the API here, which tells me the second parameter is a string.
It's perform normal in firefox. However, in chrome, it shows the errors below:
I just curious about what makes this? Is it because the api is still stay Working Draft status and different browsers do the different implementation?
The following is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentElement("beforeend",txt);
</script>
</body>
</html>
Just Change div.insertAdjacentElement to div.insertAdjacentHTML:
<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coding revoltion</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="parent">
<ul class="ul"></ul>
</div>
<script src="dom.js"></script>
</body>
</html>
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentHTML("beforeend",txt);
</script>
</body>
</html>
The parameters are incorrect. The second parameter should be html element, in your case it's a string.
Your txt variable must be an element. You can try this :
var txt = document.createElement("p")
txt.innerHTML = "testtest";
div.insertAdjacentElement("beforeend",txt);
There are two methods to insert new block of elements :
insertAdjacentElement(position, element)
The second parameter should be an element and not html text.
E.g.
var newDiv = document.createElement('div');
newDiv.style.backgroundColor = 'white';
parentElement.insertAdjacentElement('beforeend',newDiv);
insertAdjacentHTML(position, text)
text is valid html text or xml.
e.g.
var newDiv = `<div>This is a new div</div>
<p> Hello !! </p>`;
parentDiv.addAdjacentHTML('beforeend',newDiv);
first create a new html element programatically var htmlObject = document.createElement('div'); then assign your string to newly created object htmlObject.innerHTML=htmlString;.
var htmlString = `<div class="item clearfix" id="income-${obj.id}">
<div class="item__description">${obj.descripiton}</div>
<div class="right clearfix">
<div class="item__value">${obj.value}</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>`
var htmlObject = document.createElement('div');
htmlObject.innerHTML=htmlString;
document.querySelector(".income__list").insertAdjacentElement('beforeend', htmlObject);
You can use either Obj.innerHTML or Obj.insertAdjacentHTML() if you want to continue with String HTML
const html = `
<li>enter code here
<div class="collapsible-header grey lighten-4">${ title }</div>
<div class="collapsible-body white">${ content }</div>enter code here
</li>
`;
PARENTELEMENT.insertAdjacentHTML('beforeend', html);
I have change div.insertAdjacentElement to div.insertAdjacentHTML:
and it will work for me

Javascript Show/Hide elements, why isn't this code working?

So, as you can see I amusing javascript to show/hide elements, however when you click the .png it shows the text but does not hide the other element's text. I have been going over and over this script and Google searching the hell out of it and I cannot come up with an answer. I think I need another pair of eyes, so if anyone takes a look at this let me know if there are errors or if I'm missing some code.
<html>
<head>
<meta name = "viewport" content = "initial-scale = 1.0, user-scalable = no" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="NKit.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
function showStuff(id) {
document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
document.getElementById(id).style.display = 'none';
}
</script>
</head>
<body>
<div class="content">
<section class="left">
<p>
<img src="character1.png" id="char1" />
</p>
<p>
<img src="character2.png" id="char2" />
</p>
</section>
<section class="right">
<span id="character1" style="display: none;">Show character1 information</span>
<span id="character2" style="display: none;">Character 2 information</span>
</section>
</div>
</body>
</html>
<a href="#" onclick="showStuff('character1');" onclick="hideStuff('character2');">
On this line, you first set the property onclick to showStuff('character1'), then you reassign it to hideStuff('character2').
So, you should wrap these two function calls into one function and then assign that function to onclick.
onclick="function() { showStuff('character1'); hideStuff('character2'); }

Categories

Resources