in my website i use one javascript file called " backend.js "
contain javascript/jquery codes for all the website pages
so, for example in a function with a line like this :
var latit = document.getElementById('lat').value;
it works fine on a page that contains id='lat'
but in other pages i got this error in console :
Uncaught TypeError: Cannot read property 'value' of null
and also with style :
Uncaught TypeError: Cannot read property 'style' of null
and it causes stop of executing my other functions below the line.
the same with any line with document.getElementById code in all my file.
i found a solution but i don't know if it's the best or there is better
my solution it to make a test for any document.getElementById in my file like this :
if (document.getElementById('lat') != null) {
var latit = document.getElementById('lat').value;
}
is it the best solution ?
No need to call getElementById twice. You can store the result of the first call in a variable.
var lat = document.getElementById('lat');
if(lat) {
var latit = lat.value;
}
If you don't want additional variables, you can also use
var latit = (document.getElementById('lat') || {}).value;
or || Object.create(null) if you are afraid Object.prototype.value might exist.
The reason you are getting those errors is that the web app you are writing has various states and not all of them have the elements you are specifying.
If this is a problem with a SPA web app (single page app), you need to effect some degree of routing so that you are only loading the appropriate javascript for each page in the app.
If this is a libary used on many pages, you need to check the page it is on and assume only the elements that should be there are there.
If this is a library only used on one page, it is a dynamically changing but non-SPA web app, and you need to check the application state and assume only the elements that should be there are there.
Related
carousel.js:5 Uncaught TypeError: Cannot read property 'children' of null**
I got this error when I'm going to ad slider to the page.
here is the js code for the error.
const track = document.querySelector('.carousel_track');
const slides = Array.from(track.children);
const dotsNav = document.querySelector('.carousel_nav');
const dots = Array.from(dotsNav.children); //here
const slideWidth = slides[0].getBoundingClientRect().width;
slides[0].style.left = 0;
slides[1].style.left = slideWidth + 'px';
Can anyone give me a solution for this? I really appreciate your help.
Apparently the error throws here const dots = Array.from(dotsNav.children); //here , though the source of error is coming from previous line.
The error hints that the track is null, which can happen when the selector didn't return any value.
Without seeing your HTML code its not so clear whats the exact reason, but its obvious that the element with class carousel_nav doesn't exist in the DOM at the moment of execution of this code.
Steps to debug:
Do the console log after acquiring the track object.
const dots = document.querySelector('.carousel_nav');
console.log('Dots are: ', dots);
...
Then on the console of the browser check the value, its probably null.
Check if the class is written correctly on the HTML element, without typos and mistakes. You can even run the js directly on the browsers console to see if the code is actually fetching .carousel_nav
If when you run your js code in browser's console and it returns actual value instead of null, but on the page load it still returns null then it can mean the carousel is being initialized by 3rd party library after certain event, most probably document.ready, you have to as well listen to the document ready event and only after that execute your code.
Sometimes just waiting for the document ready is not enough, so check the documentation of the library that you use, it should have some callback where you can execute your code exactly after the carousel is being initialized.
Might be that the carouself library that you use, need an additional parameter to render dots, do you actually see the dots in the rendered dom?
If you need more hints, provide the library name youre using and also html
P.S.
Sorry I didn't see //here comment. But the debugging steps are the same
After several years of using Jquery I have decided to learn at least basic Javascript. I have run into what is to me a strange problem.
If I have a script like this that runs on page 1, but do not have the same class's on page 2, all scripts stop running that come after this script.
var numberOfClasses = document.querySelectorAll("li.line");
document.querySelector("p.classes").innerHTML = 'Number of support Links ' + numberOfClasses.length;
If I do not have the "p.classes" on the second page, nothing in the JavaScript file that comes after code that will run. Is this normal? The code is in a JS file that is included at the bottom of the html file on both pages. The code above is for example only
The error message on the second page is TypeError: document.getElementById(...) is null, which refers to the first bit of code in the JS file that is not present on the 2nd page
Thanks for your time
jQuery silently "fails" for these situations. If it doesn't find a selector it just returns an empty jQuery object that you can still call methods from, though they wont do anything.
Example
jQuery('NonExistentElement').html("won't show up")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No error will be thrown.
Native DOM methods like querySelector() don't return an empty object that you can still access methods from. They will either return the element, a list of elements (NodeList,HTMLCollection, etc) or null. Thus if you try to access a property on a return value from one of these you have a potential for failure in the case of a null return
document.querySelector('NonExistentElement').innerHTML = "Won't show up";
This is why you need to check for null before trying to use it
var element = document.querySelector('p.classes');
if(element != null){
element.innerHTML = "your html";
}
var element2 = document.querySelector('p.classes2');
if(element2 != null){
element2.innerHTML = "no error as the if statement fails and so this code wont execute";
}
<p class="classes"></p>
I have a classic asp project. In one of my pages i have to call a javascript function. That call does not have any problem and works fine on my test server (not localhost, just a server to test he project). But when i deploy it to the actual server, that function does not work. I call this function in onload event.
That function has this type of lines (i cannot write the whole code, because of the company that i work for, does not allow it)
document.getElementById("R6C2_1").style.display = 'block'
document.getElementById("R6C2_2").style.display = 'none'
....
When I try to debug it on IE10, i got "Unable to get property 'style' of undefined or null reference" error. After that, the elements in javascript function are not load. They are not seen on the page.
My main problem is, as i mentioned before differences between servers. I do not understand why it works on one server, but not on another server.
While it's not possible to determine the issue from this information alone, you should look into:
Whether the elements you're looking for actually exist when the code is invoked (use browser debug / breakpoints to look at the page the moment the code is invoked).
If they exist, check if they have the ID you expect (e.g R6C2_1) - if not, why? who creates these IDs? could be a server configuration issue.
Do a debug using the app from each server, and look at the page / DOM, see if there are differences or check if the code is invoked at different times.
These could lead you to pinpoint the issue. Good luck!
In case the elements just take time to be created, you can just wait until they are present:
function ExecuteWhenExists() {
var R6C2_1 = document.getElementById("R6C2_1");
var R6C2_2 = document.getElementById("R6C2_2");
if (R6C2_1 && R6C2_2) {
R6C2_1.style.display = 'block';
R6C2_2.style.display = 'none';
} else {
window.setTimeout(ExecuteWhenExists, 100);
}
}
ExecuteWhenExists();
This will not crash when the elements do not exist, and will just keep trying to execute in a non-blocking way (polling every 0.1 seconds) until they exist.
Trying to run next example http://kirjs.github.io/react-highcharts
Stuck with line:
global.HighchartsAdapter = require('exports?HighchartsAdapter!highcharts-standalone-adapter');
Without it, get error
Uncaught TypeError: Cannot set property 'HighchartsAdapter' of undefined
With it, obviously get
Cannot find module 'exports?HighchartsAdapter!highcharts-standalone-adapter'
So, the real question is how to include HighchartsAdapter.
P.S. The title of this question is different because it was my original google request. And I am not alone https://github.com/kirjs/react-highcharts/search?q=Cannot+set+property+%27HighchartsAdapter%27+of+undefined&type=Issues&utf8=%E2%9C%93
The original example should be bundled using webpack. Then I suppose it works fine.
If you want to use Browserify, then instead of using:
global.HighchartsAdapter = require('exports?HighchartsAdapter!highcharts-standalone-adapter');
var Highcharts = require("highcharts");
use next:
var Highcharts = require('highcharts-browserify');
I'm building a Squarespace page, and I want to have an outgoing link on the page whose query parameters are set according to query parameters on the page itself. Since Squarespace embeds YUI3 in every site automatically, I'm trying to use that (even though I have more experience with jquery).
Example: The page is loaded as http://example.com/page/?email=foo#bar.com. I have a link on the page that goes to http://another.example.com/page which should be modified to go to http://another.example.com/page?address=foo#bar.com.
The following code does exactly what I need when I paste it in the browser console:
var MyButton = Y.all('a[href="http://another.example.com/page"]');
var QueryString = Y.QueryString.parse(window.location.search.substring(1));
MyButton.setAttribute('href','http://another.example.com/page?address=' + QueryString.email);
However, when I put that code in the page source, then when the page loads, the following error appears in the console: Uncaught TypeError: Y.QueryString.parse is not a function
My current theory is that YUI3 loads asynchronously in pieces, and this code runs at a point when Y.all is available but Y.QueryString.parse is not... is that right? What would be the best solution to this?
Yui3 is indeed built around asychonous modules loading, in this case you miss the querystring module.
You need to wrap your code with a Y.use call:
Y.use('querystring', function(Y) {
var MyButton = Y.all('a[href="http://another.example.com/page"]');
var QueryString = Y.QueryString.parse(window.location.search.substring(1));
MyButton.setAttribute('href', 'http://another.example.com/page?address=' + QueryString.email);
});