I am facing an issue while setting the innerHTML of a div element to "". The element does exist when i first load it.
I use a drop down on my HTML page. On change in option i want to clear all the contents and replace it with new SVG elements.
Error: Uncaught TypeError: Cannot set property 'innerHTML' of null
I understand that the error is thrown because the Element it tries to retrieve is not found.
My question is: After initial load of the page, the element is created and the element "movieNetwork" has contents within it.
But when i a run the code to clear the innerHTML on change in dropdown options, it gives out Cannot set property 'innerHTML' of null error
Kindly let me know what might be the issue.
The below is the code snippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Network</title>
<link rel="stylesheet" href="movie-network.css"/>
<link rel="shortcut icon" href="popcha.ico" type="image/x-icon">
<script type="text/javascript" src="movie-network.js"></script>
<script type="text/javascript" src="movieJson.js"></script>
<script>
// Sniff MSIE version
// http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
var ie = ( function() {
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML='<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',all[0]
);
return v > 4 ? v : undef;
}() );
function takeAction() {
if( ie && ie < 9 ) {
D3notok();
} else {
// Load D3.js, and once loaded do our stuff
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "d3.v3.min.js";
script.addEventListener('load', D3ok, false);
script.onload = "D3ok();";
head.appendChild(script);
}
}
</script>
</head>
<body onload="takeAction();">
<div id ="selectoptionsMenu">
<select id="selectoption" onchange="changeGraph()">
<option value="eigen">Eigen Betweeness Centrality</option>
<option value="central">Eigen Centrality</option>
<option value="cluster">Cluster</option>
<option value="transaction">Transaction</option>
<option value="transaction">MediaSweep</option>
</select>
</div>
<div id="nocontent">
<h1>Sadly your browser is not compatible with this site</h1>
<div>You can use <a href="http://www.google.com/chrome/">Google
Chrome</a>, Mozilla Firefox
or <a href="http://windows.microsoft.com/en-us/internet-explorer/download-ie">Microsoft
Internet Explorer (v9 or above)</a> to access the PopCha Movie
Network</div>
</div>
<div id="movieNetwork"></div>
<div>
<script type="text/javascript">
function changeGraph()
{
document.getElementById(movieNetwork).innerHTML = ""; //ERROR
D3ok();
}
</script>
</div>
<div id="sidepanel">
<div id="title">
<br/>Customer Network<br/>
</div>
<div id="movieInfo" class="panel_off"></div>
</div>
</body>
</html>
Because you've written this line:
document.getElementById(movieNetwork).innerHTML = ""; //ERROR
... which is referencing a movieNetwork variable you never declared. So you're calling document.getElementById(undefined), which returns null, then effectively writing null.innerHTML = "";. Hence your Cannot set property 'innerHTML' of null error.
You probably need quotes around it:
document.getElementById("movieNetwork").innerHTML = "";
I believe you need to add quotes to the value in your getElementByID
change it to:
document.getElementById("movieNetwork").innerHTML = "";
Ok i did one hell of a stupid mistake.
I forgot the quotes and started looking at other section of the code for errors
document.getElementById("movieNetwork").innerHTML = "";
Should start listening to my dad and start wearing those glasses. Thank you guys for such a quick reply :)
The problem is you need to pass the id of the element to document.getElementById(), but you are passing a dom element reference(Since movieNetwork is the id of the element that gets copied as a property of the window object) so even if you have not declared movieNetwork that is referring to a dom element reference.
In your case you need to pass a string literal like
document.getElementById('movieNetwork')
Or in html5 browsers you could just say
movieNetwork.innerHTML = "";
movieNetwork should be a string. As movieNetwork is undefined, document.getElementById(movieNetwork) will just return null.
Working code:
function changeGraph()
{
// Changed movieNetwork to "movieNetwork".
document.getElementById("movieNetwork").innerHTML = "";
D3ok();
}
Note that the argument passed into document.getElementById() should always be a string.
Related
I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why?
$(document).ready(function() {
function Pirate(rank, phrase, id) {
output = "";
randNum = 1;
secretNum = 1;
this.strRank = rank;
this.intNum = favnum;
this.strPhrase = phrase;
this.elOutput = document.getElementById(id);
this.speak = function() {
this.elOutput.innerHTML += "<br>" + this.strPhrase;
}; //End speak
this.chooseRandNum = function() {
this.randNum = Math.floor(Math.random() * 10);
}; //End chooseRandNum
}; //End Pirate
var Captain = new Pirate("Captain", "", "captain");
var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1");
var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2");
var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3");
Captain.strPhrase = "Argh maties, ready to play a guessing game?";
Captain.speak();
}); // end of $(document).ready()
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Begin every html page with everything up to this point (just use your own header block) -->
<!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. -->
<!-- This <title> displays in the page tab -->
<title>Randomness</title>
<!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. -->
<link rel="stylesheet" href="css/myFancyStylesheet.css">
<!-- This links to the jQuery library so your js code will work
Always include this *before* your own js code (extremely important) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This links to the js code specific for this page -->
<script src="Randomness.js"></script>
</head>
<body>
Captain's Guessing Game:
<br></br>
<div id="captain">
</div>
<br></br>
<div id="pirate1">
</div>
<br></br>
<div id="pirate2">
</div>
<br></br>
<div id="pirate3">
</div>
</body>
</html>
When I run your code, I get an error message:
Uncaught ReferenceError: favnum is not defined
If you comment out this line...
// this.intNum = favnum;
...everything should work just fine.
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
<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>
Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}
I am beginner to Javascript, Trying to access object function using variable name but its giving some error. this is just dummy code if some one can correct me what I am doing worng here.. What is best method to do it.
<html>
<head>
<title>Pub/Sub Test</title>
</head>
<body>
<div id="wrap1" data-components="tooltip">
<p><h1>pubsubz Test</h1>
<p>Run with Firebug or a console simulator open.</p></p>
</div>
<div id="wrap2" data-components="tooltip">
<p><h1>pubsubz Test</h1>
<p>Run with Firebug or a console simulator open.</p></p>
</div>
<div id="wrap3" data-components="tooltip">
<p><h1>pubsubz Test</h1>
<p>Run with Firebug or a console simulator open.</p></p>
</div>
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script>
var r=r||{};
(function(tooltip,$,w,d,undefined){
var pos,
attr="data-options",
defaultSetting = {
horizontal : true,
vertical : "above"
};
tooltip.init = function($el){
alert("hello");
}
})(r.tooltip = r.tooltip || {},jQuery,window,document);
(function(r,$){
var els = {
$body : $('body')
};
// identify modules
var $modules = els.$body.find('[data-components]');
// create queue from modules
$modules.each(function(i,v){
var $module=$(this).data('components'); //value = tooltip
//want to excute r.tooltip.init() function but there is some error - $module contain value tooltip
r.$module.init();
});
})(r=r||{},jQuery);
</script>
</body>
</html>
When you want to access a property whose name you have in a variable, the correct form is
r[$module].init();