最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property toggle of undefined in one place, but works in another - Stack Overflow

programmeradmin1浏览0评论

I'm trying to make a way to expand some content if someone clicks on the title. At first spot I had to "highlight" the clicked elements as kind of a "shopping list". I did this by applying a class and worked perfectly.

At second spot I am supposed to click on an h3 element that will then expand an div element that has almost same name by also applying a class. I will show example below but problem bees that for some reason everything is undefined.

I thought maybe the reason a crucial variable was undefined is because the code executes before the HTML loads, so I wrapped it inside window.onload, this did work on first place but not second.

First place, WORKING

       <button class="btn-shop" id="almonds">Almonds</button>
       <button class="btn-shop" id="apple">Apple</button>
       <button class="btn-shop" id="argula">Argula</button>
window.onload = function(){
    var ingredientsArray = document.querySelectorAll("#almonds, 
    #argula, #apple");
    ingredientsArray.forEach(function(element){
        element.addEventListener("click", function(){
            element.classList.toggle("active-shop");
        });
    });
};

Second Place, NOT working

       <h3 id="reps">Reps</h3>
       <div class="reps-toggle noshow">
              <p>aaaaaaaaaaa</p>
       </div>
       <h3 id="timeinterval">Time Interval</h3>
       <div class="timeinterval-toggle noshow">
              <p>aaaaaa</p>
       </div>
window.onload = function(){
    var trainingType = document.querySelectorAll("#reps, #timeinterval, 
    #tabata");
    trainingType.forEach(function(element){
        element.addEventListener("click", function(){
            var elementAndToggle = element + "-toggle";
            elementAndToggle.classList.toggle("noshow");
        });
    });

Complete error message:

Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLHeadingElement. (script.js:6)

Tried console.logging some of the variables. All the values are undefined, trainingType, element, elementAndToggle. I dont' understand why.

I would like to not only have solution but, for someone kind to explain to me what the problem was and how this works so I can learn and not make same mistake again.

I'm trying to make a way to expand some content if someone clicks on the title. At first spot I had to "highlight" the clicked elements as kind of a "shopping list". I did this by applying a class and worked perfectly.

At second spot I am supposed to click on an h3 element that will then expand an div element that has almost same name by also applying a class. I will show example below but problem bees that for some reason everything is undefined.

I thought maybe the reason a crucial variable was undefined is because the code executes before the HTML loads, so I wrapped it inside window.onload, this did work on first place but not second.

First place, WORKING

       <button class="btn-shop" id="almonds">Almonds</button>
       <button class="btn-shop" id="apple">Apple</button>
       <button class="btn-shop" id="argula">Argula</button>
window.onload = function(){
    var ingredientsArray = document.querySelectorAll("#almonds, 
    #argula, #apple");
    ingredientsArray.forEach(function(element){
        element.addEventListener("click", function(){
            element.classList.toggle("active-shop");
        });
    });
};

Second Place, NOT working

       <h3 id="reps">Reps</h3>
       <div class="reps-toggle noshow">
              <p>aaaaaaaaaaa</p>
       </div>
       <h3 id="timeinterval">Time Interval</h3>
       <div class="timeinterval-toggle noshow">
              <p>aaaaaa</p>
       </div>
window.onload = function(){
    var trainingType = document.querySelectorAll("#reps, #timeinterval, 
    #tabata");
    trainingType.forEach(function(element){
        element.addEventListener("click", function(){
            var elementAndToggle = element + "-toggle";
            elementAndToggle.classList.toggle("noshow");
        });
    });

Complete error message:

Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLHeadingElement. (script.js:6)

Tried console.logging some of the variables. All the values are undefined, trainingType, element, elementAndToggle. I dont' understand why.

I would like to not only have solution but, for someone kind to explain to me what the problem was and how this works so I can learn and not make same mistake again.

Share Improve this question edited Jul 10, 2019 at 17:38 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Jul 10, 2019 at 17:33 Filip HrnjezFilip Hrnjez 371 gold badge1 silver badge8 bronze badges 7
  • 1 elementAndToggle is a string. Strings do not have a classList property. Set a breakpoint on that line. – user47589 Commented Jul 10, 2019 at 17:37
  • Ok that makes more sense, unfortunately i didnt understand what you mean by set a breakpoint on that line. Would you mind helping me out a bit? Thanks for quick response. – Filip Hrnjez Commented Jul 10, 2019 at 17:40
  • Specifically, doing element + "-toggle" does not work in a meaningful way. It produces a string like "[object HTMLElement]-toggle". – Heretic Monkey Commented Jul 10, 2019 at 17:41
  • @randomSoul That doesn't matter; toggle will add the class even if none exist... – Heretic Monkey Commented Jul 10, 2019 at 17:41
  • 1 @FilipHrnjez Google the name of your browser and "how to set breakpoints". Knowing how to use a debugger is an essential skill for development. It is worth taking the time to learn. – user47589 Commented Jul 10, 2019 at 17:42
 |  Show 2 more ments

1 Answer 1

Reset to default 2

The problem is with your elementAndToggle variable.

Within trainingType.forEach, you refer to each element in the page matching your querySelectorAll. Immediately after that, you set the value of elementAndToggle to the element itself, and concatenate a string to it. This causes the variable's value to bee a string like [object HTMLElement]-toggle.

It looks like you're trying to retrieve the id of each element, append something to it, then query a similar element based on its class. You can do this with:

var elementAndToggle = element.id + "-toggle";
document.getElementsByClassName(elementAndToggle)[0].classList.toggle("noshow");

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论