document.getElementById().children.length - Cannot read property 'children' of null [duplicate] - javascript

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.
Saw this error on the console -
VM2134:1 Uncaught TypeError: Cannot read property 'children' of null
I think this is where it happened -
if (document.getElementById('confirmMsg').children.length > 0) {
document.getElementById('confirm').classList.add('ui-state-error')
}
else {
document.getElementById('confirm').classList.remove('ui-state-error')
}
I'm not familiar with javascript but I feel like I need to make sure that element exists && has children? Please help fix this issue. Thank you!

Did you put this code before or after the actual HTML? Because this could generate an error if the element isn't yet loaded.
A more obvious answer would be "heh, there's no such ID in the DOM" :)
And finally, you could do a test in order not to get this error...
Something along those lines:
function foo() {
if (document.getElementById('confirmMsg')) {
if (document.getElementById('confirmMsg').children.length > 0) {
document.getElementById('confirm').classList.add('ui-state-error')
} else {
document.getElementById('confirm').classList.remove('ui-state-error')
}
} else setTimeout(foo, 1000);
}
Would call itself until the element exists, and then do the expected stuff.
I know there must be a cleaner and prettier way to do this, I was just trying to get the idea down :)

Related

How do I prevent TypeError blank is undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 3 years ago.
Is there an easier way to check if a variable is defined or not in JavaScript when the target is deep within an object?
For example.
// Lets assume this:
response = {
status: "simple-message"
}
// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined
In PHP I can run the equivalent check:
if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error
I know I can iterate manually by checking each item starting with the root to see if it's defined, but that seems tedious. That and wrapping everything in a try/catch.
Is there a cleaner / faster / smarter way to do this?
Use
try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}

Property 'id' does not exist on type 'EventTarget' thrown when working with event.target.id [duplicate]

This question already has answers here:
Property 'value' does not exist on type 'EventTarget'
(17 answers)
Closed 8 months ago.
I am attempting to perform a HostListener on my component, specifying that I want something to happen when anything BUT a specific element is clicked; however, I am receiving the error:
Property 'id' does not exist on type 'EventTarget'
The code runs fine in the UI, but I can't shake this error thrown by linting.
I understand that I must use a type for the this, such as if I were performing it about an input element. However I am performing the check on a normal <div> that is being clicked...
I am unsure of how to proceed.
#HostListener('document:click', [$event'])
myClick(event: MouseClick): void {
if (event.target.id !== 'some-id') {
// do something here
}
}
I have been playing around with something such as:
if (<HTMLElement>event.target.id...
but I cannot find a fix for this...
I will post #ConnorsFan's answer since his comment worked out for me.
In the end I went with using (<HTMLElement>event.target).id.
It seems that my attempt at setting event.target.id was misguided as I understand now that the type should be applied to the target, and the ID is just an attribute of said target element.

Javascript - how to check if the parent object is not undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I find I'm doing this, whereby I need to check that the preceeding variable is not undefined before checking the next one in the chain:
if( this.props.someVar && this.props.someVar.data ) {
// do something with this.props.someVar.data ...
}
It would be ideal just to do this:
if( this.props.someVar.data ) {
// This throws an error because I haven't checked if `this.props.someVar` exists beforehand.
}
Is there an easier/shorter way to so this, preferably using pure Javascript?
I hate that too. The easiest way is to use try catch like this
try {
// do something with this.props.someVar.data
} catch (e) {
if (e instanceof TypeError) {
// TypeError happens when an object in the chain is undefined
}
}

jQuery: What does jQuery return when the jQuery object can't find a specified class selector? [duplicate]

This question already has answers here:
Check if element exists in jQuery [duplicate]
(8 answers)
Closed 6 years ago.
Let's say we have:
var $letsTestA = $( '.lets-test-a' ),
$letsTestB = $( '.lets-test-b' );
While the HTML is:
<div class="lets-test-a"></div>
(I know, I left out .lets-test-b)
Now, what happens if we try to call the variable $letsTestB?
I did do some testing, I'm not just blindly asking a question without doing some research first, but I'm a little confused with how this seems to work...
If I alert($letsTestA); or alert($letsTestB); I get the same outcome which is just [object Object] when testing from JSFiddle?
Here's my test fiddle: https://jsfiddle.net/m6j03423/
Furthermore to this, what I'm actually trying to do here is create a way to find out whether the content of a variable exists or not.
In PHP I would just write if (empty($myVar)) { // do action } but JS doesn't work the same way.
In JS I think I can write if ($letsTestA) { } and it should be able to print the result of the variable? But, I'm still getting [object Object].
What am I missing?
Can I even print the contents of a jQuery object?
How can I test whether the variable contains the true value of a jQuery object?
EDIT:
Admittedly, I did see a few different answers saying to check the length, but I didn't understand that enough to connect that to what I'm doing.
You can use the .length property of the object to ascertain whether elements exists or not
if ($letsTestA.length > 0) {
//element exists
}
var $letsTestA = $('.lets-test-a'),
$letsTestB = $('.lets-test-b');
console.log($letsTestA.length);
console.log($letsTestB.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lets-test-a"></div>

Check if variable is undefined not working [duplicate]

This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 6 years ago.
I want to check if a variable is undefined and quickly found some stackoverflow answers that said the correct way to do it is to test if(variable==null). But in Chrome I am getting an error saying:
Uncaught ReferenceError: xdate is not defined
Huh? The whole reason I am testing is so I don't get errors like this. And I did it just like the approved stackoverflow answers.
Here is my code snippet.
if (xdate == null){
var dateadd = "";
} else {
var dateadd = "&date="+date;
}
use something like this to verify whether variable is undefined or not
if (typeof something === "undefined") {
alert("something is undefined");
}

Categories