Click here to Skip to main content
15,917,795 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, I have this code to get a parameter for the matching selector:
JavaScript
// If the event category is not set on the current element, look for a parent that has it.
if (_.isEmpty(fileType) || fileType.trim() === '') {
trackingElement = trackingElement.closest('[data-tracking-filetype]');
	 if (trackingElement) {
		fileType = trackingElement.dataset.trackingFiletype;
    }
}


Unfortunately, not always such element in DOM exists and then I am getting a following error in the console:
Uncaught TypeError: can't access property "closest", trackingElement is null


What I have tried:

I have tried to use the querySelector() instead of closest() method.
Also tried to use optional chaining, which got rid of the error in the console BUT caused the fileType value to be undefined, whereas in the past it has been working (save for the error in the console):
JavaScript
if (_.isEmpty(fileType) || fileType.trim() === '') {
	trackingElement = trackingElement?.closest('[data-tracking-filetype]');
			if (trackingElement) {
				fileType = trackingElement.dataset.trackingFiletype;
	}
}


Anyone knows how to fix it?
Posted
Comments
Chris Copeland 15-Nov-22 8:10am    
As you say, trackingElement.closest('[data-tracking-filetype]'); throws an error because trackingElement is null. You need to investigate why it's null. If you're always expecting the value to be non-null then you need to take a look at the part of the code where it finds that element. That's a part of code which we can't see, so can't provide any help with.
Afzaal Ahmad Zeeshan 15-Nov-22 8:15am    
Applying the null-safety operator will only hide the problem; instead of using the operator, find out why the element is null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900