Jonas Krat Frank
Jonas Krat Frank

Reputation: 1

I am looking for the reason why I get TypeError: x is undefined

I get an error when running my code, but it does remove the elements as expected.

I have tried to use a querySelectorAll but that gave me "slet.style is undefined"

    if (document.URL.indexOf("/catalog/categories/departments/") > -1) {
    var allProducts = document.getElementsByClassName("threeColumn product");
    for (var i = 0; i < allProducts.length; i++) {

    var slet = document.getElementsByTagName("mark")[i];
    slet.style.display = "none";
    console.log("This is here now");
        }
   }

I want the code to not display the element named mark on all pages that include /catalog/categories/departments/ in the URL. It does display:none but i get an error message:

"TypeError: slet is undefined" But I think I already defined it in the "slet" var?  

Upvotes: 0

Views: 401

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

If document.getElementsByTagName() returns an empty HTMLCollection, then document.getElementsByTagName()[i] returns undefined, so slet IS undefined. It doesn't mean your variable slet does not exist - which would raise a ReferenceError - but that it's value is the special undefined object.

Upvotes: 1

Related Questions