TypeError: getElementById is null - javascript

<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"

Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).

It should be document.getElementById('submit').onclick(clicked());

your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');

You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>

Related

Removing first string character with substr in WordPress

I am trying to remove the "|" from the file size span tag. The syntax of my javascript code so far does look fine, but it's not working quite yet.
From my understanding I am using the proper syntax for substr: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
In Chrome, I am getting this console error:
Uncaught TypeError: Cannot read property 'substr' of undefined
In Firefox, I am getting this console error:
Uncaught TypeError: innerTextString is undefined.
Also the "|" isn't being removed as intended. Any ideas where I am going wrong here?
Thank you in advance.
<script>
const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');
const innerTextString = prettyLinkRightFileSize.innerText;
innerTextString.substr(0);
</script>
.prettyFileList .float_right {
float: right;
}
<div class="prettyFileList">
<div>
<a href="#" class="prettylink">
<span class="float_right">| Size 150 KB</span>
<span class="float_right">28th Jan 2021</span>
</a>
</div>
</div>
You do not crop anything, when you use innerTextString.substr(0), as it has the same amount of characters like the original String.
var e = "ThisisaText";
var t = e.substring(0);
Log.v("e", e);
Log.v("t", t);
Output:
"ThisisaText"
"ThisisaText"
additionally you select the Items via classname. So I recommend, you crop all Items with the same class to provide consistency.
Try this code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="prettyFileList">| Testsize</div>
</body>
<script>
var c = document.getElementsByClassName('prettyFileList');
for (var i = 0; i < c.length; ++i) {
var item = c[i];
item.innerHTML = item.innerHTML.substr(1);
}
</script>
</html>
querySelectorAll() returns a static (not live) NodeList. You need to use prettyLinkRightFileSize[0].innerText.
const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');
const innerTextString = prettyLinkRightFileSize.innerText;
To
const prettyLinkRightFileSize = document.querySelector('.prettyFileList .float_right:nth-child(1)');`
let innerTextString = prettyLinkRightFileSize.innerText;
innerTextString = innerTextString.slice(1);
console.log(innerTextString)
This will do the job:
<script>
Array.from(document.querySelectorAll('.prettyFileList .float_right:first-child'))
.map(element => element.innerText = element.innerText.substring(1));
</script>
It also works with multiple elements on your page!
If you do querySelectorAll you will get a nodeList with all elements matching the select statement. You have to iterate over these results to manipulate each of them (also if you only match one element: An array with one element still requires other treatment than the element it self).

JavaScript set interval not working?

Could someone please explain why the following code below doesn't run an automated sequence of images'. I was able to do this before with my code prior to this now that I have edited it slightly the automation doesn't work.
<!DOCTYPE html>
<html>
<body>
<img id="Light" src="./red.jpg">
<button type="button" onclick="ChangeLights()">Change Lights</button>
<script>
var List = [
"./red.jpg",
"./redyellow.jpg",
"./green.jpg",
"./yellow.jpg",
];
window.onload = "ChangeLights()";
var index = -1;
function ChangeLights() {
index ++;
var image = document.getElementById('Light');
image.src = List[index % List.length];
}
setInterval(ChangeLights, 1000)
</script>
</body>
</html>
It works fine, but you can change Array to a different name and call ChangeLights(); without "" in line 18 .
The automation works, but the path to the images is wrong, you should fix that by pointing to the right folder, probably by removing the "./" on "./NAME_OF_THE_IMAGE".

Toggle text with JavaScript

I am learning JavaScript.
I am trying toggle the text on a page using the replaceChild() method. I came up with the code below. I don't understand why it will not work. Pls help.
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
if (b4[0].innerHTML=="Before"){
be.replaceChild(l8,b4[0])
}
if (b4[0].innerHTML=="After") {
be.replaceChild(l88,b4[0]);
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>
As CBrone wrote, you have to create h1 instance first, store it to variable and then call innerHML on the variable.
Another problem is if structure. First you replace the element and then test the same element for another condition and do another operation. In this case is better to use if ... else if ... statement instead of if ... if ..., which is the root of your problem.
Here is working toggleText function
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
l88.innerHTML="Before";
if (b4[0].innerHTML == "Before")
{
be.replaceChild(l8, b4[0]);
}
else if (b4[0].innerHTML=="After")
{
be.replaceChild(l88, b4[0]);
}
}
Here is working fiddle
In addition to what’s been said in comments already:
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
After this your variables do not contain references to the created elements, but the string values that you assigned to their innterHTML. (The result of an assignment operation is the assigned value.) And trying to pass text values instead of element references to replaceChild afterwards must fail for that reason.
Do this in two steps – create the elements first and save their reference into the variables – and then manipulate their innerHTML afterwards.
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
var l88 = .innerHTML="Before";
(And maybe use better suited variable names, because if you keep your current “naming scene” up you’ll get confused sooner or later.)
May I suggest the following, for better readability:
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1")[0];
if (b4.innerHTML=="Before") {
b4.innerHTML = "After";
}
else if (b4.innerHTML=="After") {
b4.innerHTML = "Before";
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

.innerHTML problems storing it into a variable

Here is my code that is not working - thanks guys - first question!
<html>
<head>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
</script>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
Also sorry for the update but do you guys have an idea of how to do this when the div is in an iframe thats not on the same domain? Thanks
This line
var x = document.getElementById("myElementId").innerHTML;
is executed before the element with ID myElementId exists, so JavaScript cannot find it (getElementById returns null).
Put it after the element:
<div id="myElementId">24</div>
<script>
var x = document.getElementById("myElementId").innerHTML;
</script>
The HTML document is processed from top to bottom.
You're running this line:
var x =document.getElementById("myElementId").innerHTML;
before the element exists. Remove the script from the head an put that line right before:
if(x < 25) {
Instead.
In addition to the creating the element first,
I believe innerHtml returns a string value
Try parsing it first;
var value = document.getElementById("myElementId").innerHTML;
var x = parseInt(value,10)
change it to:
<html>
<head>
</head>
<body>
<div id="myElementId">24</div>
<div>
<script type="text/javascript">
var x =document.getElementById("myElementId").innerHTML;
if (x < 25) {
document.write("worked")
}
else {
document.write("didn't work")
}
</script>
the element that you are trying to look for does not even exist on the page when you run the script that is why you have run into this issue..
document.getElementById("myElementId").innerHTML;
You have to use a # with Id and . with class in it
document.getElementById("#myElementId").innerHTML;

Categories

Resources