This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
<!-- This is the HTML element -->
<h1 id="greeting"></h1>
JS
var currentUser = localStorage.getItem("currentUser");
document.getElementById("greeting").innerHTML = "Hi " + currentUser;
Here is what happens when inspect the page, it says:
Uncaught TypeError: Cannot set property 'innerHTML' of null(…)
This would be the entire code file.
//mypublicwebsites.tk/artem/databases/a/load_home.js
//This isn't the complete code because I cannot use 'localStorage' in a code snippet
//excluding unneeded code
var isSignedIn = true;
//The current user, lets just say that is me
var currentUser = "Sean";
if(isSignedIn) {
load();
} else {
window.location.replace("index.html");
}
function logOut () {
localStorage.setItem("isSignedIn","false");
localStorage.setItem("currentUser", "none");
window.location.replace("index.html");
}
function load() {
document.querySelector(".greeting").innerHTML = "Hi " + currentUser + "!";
}
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="mypublicwebsite.tk/artem/databases/a/load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
It does seem to work in the snippet but not in the browser.
Fine, I'll post the answer I found. You need to wait for the webpage to load and then execute the script, so I put the script right before the closing body tag.
After checking your source over at Github i notice that there is no element of id greeting at https://github.com/codecademy123/codecademy123.github.io/blob/master/artem/databases/a/home.html :
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
No id but there is a class with the name greeting.
Here's an updated and simplified fiddle:
https://jsfiddle.net/tommiehansen/ndd0c7rh/2/
Basically we just use document.querySelector('.greeting') instead of document.getElementById('greeting') since the id greeting will always return undefined if it does not exist.
If you want to still use an id simply change the source code for home.html from <h1 class="greeting"></h1> to <h1 id="greeting"></h1>. The important part here is to query the DOM after what you've set the class or id to be. Because if you do not match these it will always return as undefined since your javascript will not be able to find the selector.
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed last year.
I am a JavaScript beginner and when I was making a HTML, CSS, JS project with VSCode, I encountered the following error:
Uncaught TypeError: Cannot read properties of null (reading at 'addEventListener')
Also, My project was: Make a login + register system with just JavaScript dictionaries, and a logged_in variable (that will redirect people to the registration page if it's false)
HTML Registration file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>BeedHub Register</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
<script src='index.js'></script>
</head>
<body>
<h1 class="hello_world">Welcome!</h1>
<p class="aaa">We're so excited to see you!</p>
<div class="usernamediv">
<input id="main_usr" placeholder="Write username here" type="text">
</div>
<div class="passworddiv">
<input id="main_pw" placeholder="Write password here" type="password">
</div>
<div class="btn">
<button id="main_register">Register!</button>
</div>
<div class="login_instead">
Login Instead
</div>
</body>
</html>
JavaScript file:
// Variables
var db = {
};
var logged_in = false;
// Register Elements
var rg_usr = document.getElementById("main_usr");
var rg_pw = document.getElementById("main_pw");
var rg_submit = document.getElementById("main_register");
// Event Listeners
rg_submit.addEventListener('click',function() {
if (db[rg_usr.innerHTML]) {
var error_usr_taken = document.createElement("p");
error_usr_taken.innerHTML = "Error: Username Already Taken!";
} else if (rg_usr.innerHTML == "" || null) {
var error_usr_none = document.createElement("p");
error_usr_none.innerHTML = "Error: Username is null!";
} else if (rg_pw.innerHTML == "" || null) {
var error_pw_none = document.createElement("p");
error_pw_none.innerHTML = "Error: Password is null!";
} else {
db[rg_usr.innerHTML] = rg_pw.innerHTML;
logged_in = true;
window.location.pathname = "/successpage";
};
});
If you want me to provide more information, comment with a ping.
P.S. I have also used the script tag on my /login/index.html file, but the web says that multiple HTML files using the same JavaScript file have no problem.
Thanks in advance,
Beedful
Your script is being executed before the markup is on the page and that's why you're getting an error.
So, you can either move the script tag at the very end of the body like this:
<body>
<!-- All contents here -->
<script src='index.js'></script>
</body>
Or you can add defer to your script tag and let it continue to be in the head, like this:
<script src='index.js' defer></script>
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
i want to check existence of a cookie in html,
here is my code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
$cookie_name = 'testhastin';
if(!isset($_COOKIE[$cookie_name])) {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>
but when i run this page, noting will happen for "a1 test". (meaning it does not change to "not set")
i want to check if a cookie exists on the page and if so show specific content.
i also tried this code and result was the same:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
var username = getCookie("testhastin");
if (username != "") {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>
$_COOKIE is a PHP variable. isset() is a PHP functoin. You cannot use that in JavaScript.
As for fetching cookies use document.cookiename
// Setting a cookie
document.testhastin= "Akshay";
// Reading a cookie
var val = document.testhastin;
W3Schools Link : https://www.w3schools.com/js/js_cookies.asp
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one
This question already has answers here:
How to append text to a div element?
(12 answers)
Closed 5 years ago.
<a id="Param">This is an html element</a>
<script>
function Append(param1,text)
{
if(document.getElementById(param1))
{
return document.getElementById(param1)+text;
}
else
{
console.error("the element was not found");
}
}
var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?
A string-query might be your best bet by making the PARAM dynamic and you can change it based on what the url passes to the script. index.php?param1=myvalue
Here is a reference article I used last time I had to do it myself: https://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/
Respectfully,
SFR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>
<a id="Param">This is an html element</a>
<script>
function appendToElement(p1,p2)
{
var el=document.getElementById(p1);
if(el)
{
el.innerHTML+=p2;
return true;
}
else
{
console.error("Element with ID: "+p1+" not found");
return false;
}
}
var app1=appendToElement("Anything",". yes");
var app2=appendToElement("Param",". hi")
</script>
</body>
</html>
This is the code that I got from my professor.
<html >
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function greet {
var greet = document.getElementById("greeting");
greet.value="this is dynamic";
</script>
</head>
<body>
<p onmouseover="greet()"> Hello! Welcome to My Page </p>
</html>
What is the problem in this code?
Firstly, you haven't closed your greet function (missing the closing } character). Secondly, you're missing the parentheses after the name of the function:
function greet() {
//Function body
}
Secondly, you're using getElementById to try and obtain a reference to the p element, but the p element doesn't have an id.
Thirdly, the greet variable will contain a reference to a p element, which doesn't have a value property (like, for example, input elements do). You may have meant innerHTML if you are trying to change the contents of the element.
Finally, you haven't closed your <body> element. Edit (see comments) - This isn't a problem, but personally I prefer closing it for consistency.
You could pass a reference to the element into the function when it's called, to save you having to get it by id:
<p onmouseover="greet(this);">Example</p>
And JavaScript:
function greet(elem) {
elem.innerHTML = "Something new";
}
the p element should have an ID of greet, as in:
<p onmouseover="greet()" id="greeting"> Hello! Welcome to My Page </p>
, so that when you select the element's ID at:
document.getElementById("greeting");
the document can find the tag you are trying to select from the HTML document.
Additionally, instead of editing the node's "value" attribute, I think you need to use the "innerHTML" instead. So that gives:
<html >
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function greet {
var greet = document.getElementById("greeting");
greet.innerHTML="this is dynamic";
}
</script>
</head>
</body>
<p onmouseover="greet()" id="greeting"> Hello! Welcome to My Page </p>
</html>
I am not exactly familiar with JavaScript, but I believe that should work.
You can try:
greet = function(elem) {
elem.innerHTML = "Something new";
}
or
greet = function() {
var greet = document.getElementById("greeting");
greet.innerHTML="this is dynamic";
}
Along with the other tips of course(like id attribute for the relevant <p> element and well-forming your HTML).