How to fix “Uncaught TypeError: Cannot read property ‘indexOf’ of undefined” in WordPress

We had this error “Uncaught TypeError: Cannot read property ‘indexOf’ of undefined” in WordPress a few times. First time when we encountered this, it was a little scary. If something does not work after a WordPress or plugin update or maybe because the plugins were not updated for a long time then you can check the Inspector > Console.

This is a JavaScript or jQuery error which can prevent certain things from working on your website. Like for example the WP editor is not working anymore, or something else controlled by JS is acting weird.

The problem in Console is looking something like this:

This happens because a JS variable it is not defined!

When you check, clicking the link from Console error, you will be redirected to a certain piece of code in a JS file. Like for example you can have a piece of code like this in one of your JavaScript files:

if(myVar.indexOf("something_here")<0) {

a lot of code here...

}

You can easily see that the indexOf problem refers to myVar variable!

The solution to fix Uncaught TypeError: Cannot read property ‘indexOf’ of undefined

There is a really simple fix for this JS error! All you have to do it to check if that variable is defined and if so, then execute the code. So the code will look like this:

if (myVar) {

if(myVar.indexOf("something_here")<0) {

a lot of code here...

}

}

To be more clear, you will need to open the JS file on your computer, edit it and then upload it back to FTP. This can be a plugin file, a theme file etc. So, be careful, because even if the error is fixed, when you will update the theme or the plugin it is possible that your change is overwritten. Unless that the theme or plugin developer has fixed the problem, it is possible that your problem is back. So you will need to add the code again!

Please let me know if this solution is working for you.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *