This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I am a beginner in Javascript. I am doing some exercises and coming across the error listed above for the 'onclick'.
I have looked at other questions on this forum and it has not be helpful for me. I have looked over syntax numerous times in both my html and JS and can't find anything!
var item1;
var item2;
var item3;
document.getElementById("changeList").onclick = newList;
function newList() {
item1 = prompt("Enter a new first thing:");
item2 = prompt("Enter a new second thing:");
item3 = prompt("Enter a new third thing:");
updateList();
}
function updateList() {
document.getElementById("firstThing").innerHTML = item1;
document.getElementById("secondThing").innerHTML = item2;
document.getElementById("thirdThing").innerHTML = item3;
}
<html>
<head>
<meta charset="UTF-8">
<title>Javascript Practice</title>
<script src="main.js"></script>
</head>
<body>
<h1 id="myName">Angie</h1>
<hr>
<p id="aboutMe"><em>I am trying to learn this damn javascript and stick with it.</em></p>
<h2>Things I like</h2>
<p>Here are some of the things I like to do:</p>
<ul>
<li id=firstThing>Dance</li>
<li id=secondThing>Write</li>
<li id=thirdThing>Travel</li>
</ul>
<button id="changeList" type="button">Change Your List</button>
</body>
</html>
You can try placing your script tag at the bottom of the page as suggested by lealceldeiro or you can wait for the DOM to load fully before adding your event listener for onclick like so:
//Replace this line
document.getElementById("changeList").onclick = newList;
//With the following, this fires an event when the DOM has fully loaded
//This will ensure your element has been rendered into the DOM
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("changeList").onclick = newList;
});
Try changing your html line to :
<button id="changeList" type="button" onclick = newList();>Change Your List</button>
and remove this line from your JS
document.getElementById("changeList").onclick = newList;
Related
This question already has answers here:
why the result is NaN?
(4 answers)
Closed 1 year ago.
I've tried a lot of stuff, however I don't know any JavaScript. All of the JavaScript in the code is copied from stack overflow and other sources. The only thing I know how to use is HTML and I'm still very new. (it might also include some CSS which I also don't know at all)
The <!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>--> is a failed thing so ignore it lol.
<html>
<head>
<meta charset="utf-8">
<title>Bottle Clicker</title>
</head>
<body>
<img src="Images/BigBottle.png" height="500">
<!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>-->
<br>
<br>
<input type="text" id="hydrationLevelDisplay" placeholder="Hydration Level: " disabled style= text-align:center>
<script>
var hydrationLevel = 0
function bigBottlePress() {
var hydrationLevel = hydrationLevel + 1
document.getElementById("hydrationLevelDisplay").value = "Hydration Level: " + hydrationLevel;
document.title = "Hydration Level: " + hydrationLevel;
}
</script>
</body>
</html>
You have already declared hydrationLevel outside function, so don't need to redclare it. Just change,
var hydrationLevel = hydrationLevel + 1
to
hydrationLevel = hydrationLevel + 1
create a button -> id:btn
create a result div or p or h1 -> id:hydrationLevel
select the button, add event listener
document.getElementById('btn').addEventListener('click', incrementLevel)
let hydrationCount = 0;
function incrementLevel() {
hydrationCount += 1;
document.getElementById('hydrationLevel').textContent = hydrationCount;
}
I'd encourage you to use event listeners this way. not inline that's why I provided this solution.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
i think that the code 100% normal but why i got that Error????:
Uncaught TypeError: Cannot set property 'innerHTML' of null||
the code is:
<!DoCTYPE html>
<html lang="eng">
<head>
<meta charset ="utf-8">
<meta name="" content="">
<title></title>
<script>
function myAgeInDays() {
"use strict";
var myAge = 15;
return myAge * 365;
}
var daysCalc = myAgeInDays();
document.getElementById("test").innerHTML =
"Your Age In Days = "+ daysCalc+ " Day";
</script>
</head>
<body>
<button onclick="myinfo();">OK</button>
<h1 id="test">Ok</h1>
</body>
</html>
A few things can be done to improve this question:
Give some context, not the error the console prints out
Especially in the case of a very common js error. An example for your case could be "In form submission cannot select html element / selector is null in onclick function".
State some of the things you have tried
This will help you grow as a developer (the old teaching someone to fish story)
Some more tips here: https://stackoverflow.com/help/how-to-ask
In your case, the code you posted does not work (myinfo is not defined) and your code is in the <head> which is defined before the <p> is created. add it at the end of your body to ensure that all the elements are created. If you wanted to make a function handle the button click that contained the logic in your , you would write something like:
<body>
<button id="calcDays">OK</button>
<h1 id="test">Ok</h1>
<script type="text/javascript">
document.getElementById('calcDays')
.addEventListener('click', function () {
function myAgeInDays(days) {
return days * 365;
}
document.getElementById("test").textContent =
`Your Age In Days = ${myAgeInDays(15)} Days`;
});
</script>
</body>
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
I recently starting learning JS and for some reason I cannot get getElementByClassName to work for me. Here's my code.
//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");
//coloring the id 'first'
id.style.color = "red";
cs.style.color = "blue";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Site</title>
</head>
<body>
<h1 id="first">This is an ID</h1>
<h1 class="second">This is a class</h2>
<script src="index.js"></script>
</body>
</html>
The element with an ID is changing color but the one with a class isn't. Any help would be greatly appreciated.
getElementById returns one single element as you should not have multiple element with the same Id in the DOM.
getElementsByClassName returns an HTMLCollection as many elements can share the same class name.
try this instead :
//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");
//coloring the id 'first'
id.style.color = "red";
cs[0].style.color = "blue";
In real life use case you might wanna loop through the array.
I am somewhat new to programming and have been working through the Head First HTML5 Programming book. On page 65, they have an exercise that helps you insert a javascript function into the HTML head that will change the text located at bullet points in the body of the page. When I open the HTML file in the browser, the page loads, but the content from the Javascript function isn't added to the bullet points. I have determined it's because the script is running before the DOM is complete because when I change the book's code to <body onload="addSongs()">, the page loads correctly.
Here's the code from the book (that doesn't seem to work):
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
window.onload = addSongs;
}
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>
I have read through different posts and many people suggested using JQuery (which I'm hoping to learn in the next few months), but I'm just curious as to whether the window.onload = function; has been deprecated since this book was published or if I am making a mistake somewhere. A lot of the exercises in this book use this principle and I can't move forward until I figure this out. Any suggestions or different approaches are appreciated.
Thanks!
You need to move the line:
window.onload = addSongs;
To outside the function.
"I have determined it's because the script is running before the DOM is complete"
The script is running, but all it does is declare a function, it doesn't ever call it (because the aforementioned line is in the wrong place).
it's just a typo.
you put window.onload = addSong; in the definition of the function addSong. so window.onload will never be set, as addSong will never be called.
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs; //move this line out of function definition.
You need to move window.onload = addSongs; after define the function, not before it.
like this:
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs;
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>
I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}