Search code examples
javascriptjqueryerror-handlinginnertext

How do you ignore 'cannot read property 'error in jQuery


I have made a program that creates a div element and sets the inner text of that element to the same as another div element. The text is only there sometimes (as it is to display notifications) and so for the majority of the time, the innerText property is empty.

When I run the program I keep getting the error printed to the console 'jQuery.Deferred exception: Cannot read property 'innerText' of undefined'. This is obviously because there is no text. How do I ignore this error message and not print it to the console (this is for my website and so I don't want it to be displayed).

I have tried if ( myDiv[0].innerText != "") {//code here} but that doesn't work and I have also tried a try-catch statement but that also didn't work.

Thanks


Solution

  • The error means that myDiv[0] doesn't exist. If you want to read the value you can add a check with optional chaining (?.)

    myDiv?.[0]?.innerText
    

    It's equivalent to

    myDiv && myDiv[0] && myDiv[0].innerText
    

    If you want to set the inner text you need an if condition

    if (myDiv?.[0]) {
        myDiv[0].innerText = 'new Text';
    }