Flip
Flip

Reputation: 6761

Yet Another Uncaught TypeError: : Cannot read property 'replace' of undefined

I am writing a bit of JS code to switch classes for certain DOM elements. Everything is working as it should, but I am also getting this error and this prevents the code that follows to be executed.

I added a check to make sure that the array of elements is not empty as I thought this was the problem. But still the error occurs. Debugging always showed a value for old_name when replace is called on it. Am I missing something JS-esque?

This is the part of the code that causes the error, specifically line 31:


  if (w > MOBILE_THRESHOLD) {
    responsive_elements = document.getElementsByClassName("desktop");
    if (responsive_elements.length > 0) {
      for (i in responsive_elements) {
        var old_name = responsive_elements[i].className;
        var new_name = old_name.replace("desktop", "mobile");
        responsive_elements[i].className = new_name;
      }
    }

When necessary I will be happy to provide more code, or whatever information is needed. Thanks!

Upvotes: 1

Views: 649

Answers (1)

Oriol
Oriol

Reputation: 288000

Never use for...in loops to iterate array-like objects!!!!!

In this case, the HTMLCollection has enumerable properties like item or namedItem. Accessing these won't return an HTML element, so className will be undefined.

To iterate properly, you can use one of these

for(var i=0; i<responsive_elements.length; ++i) {
  // ...
}

[].forEach.call(responsive_elements, function(element, index, collection) {
  // ...
});

Upvotes: 5

Related Questions