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

I'm trying to make a way to expand some content if someone clicks on the title. At first spot I ha

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");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745646935a4638024.html

相关推荐

  • Windows下配置Golang开发环境,并安装配置GoLand IDE

    作者&#xff1a;非妃是公主 专栏&#xff1a;《Golang》 博客地址&#xff1a;https:blog.csdnmyf_666 个性签&#xff1a;顺境不惰&#xff0c;逆境不馁

    1小时前
    00
  • 如何使用python查询Prometheus监控数据

    一.环境准备软件库包版本python3.8prometheus-api-client0.5.7二.安装步骤代码语言:python代码运行次数:0运行复制pip3 install prometheus-api-client默认安装最新版本的p

    1小时前
    20
  • windows 配置 upx

    ​1、下载:2、解压:解压后​3、配置环境变量,右键我的电脑-——》属性——》高级属性:在Path中添加: D:ProgramFileupx-5.0.0-win644、验证cmd中输入:代码语言:txt复制upx --version

    1小时前
    20
  • 打破常规!支付宝小程序地图功能开发实用技巧,拓展业务场景

    打破常规!支付宝小程序地图功能开发实用技巧,拓展业务场景嘿,各位开发者小伙伴们

    1小时前
    00
  • 利用小提琴图探索帕尔默企鹅数据

    利用小提琴图探索帕尔默企鹅数据代码语言:javascript代码运行次数:0运行复制import numpy as npimport matplotlib.pyplot as pltimport scipy.stats as stfro

    1小时前
    00
  • UMIT:统一多模态多任务视觉

    随着深度学习的迅速发展,尤其是在医学影像分析领域的应用,越来越多的视觉-语言模型(VLMs)被广泛应用于解决复杂的健康和生物医学挑战。然而,现有研究主要集中在特定任务或单一模态上,这限制了它们在多种医学场景中的适用性和泛化能力。为了解决这

    58分钟前
    00
  • 2025年最受欢迎的10款免费CRM软件大对比

    在数字化转型浪潮下,越来越多的企业开始重视客户关系管理(CRM)系统。一个高效的CRM不仅能帮助企业理清客户脉络,还能提升销售效率、优化服务体验。2025年,市场上涌现了众多优秀的免费CRM软件,本文将为大家对比10款最受欢迎的产品,助您选

    57分钟前
    00
  • 10个 DeepSeek 神级提示词,建议收藏!

    在当下人工智能飞速发展的时代,DeepSeek 作为一款功能强大的 AI 工具,能够帮助我们实现各种创意和需求。然而,要充分发挥它的潜力,掌握一些巧妙的提示词至关重要。今天,就为大家精心整理了 15 个 DeepSeek 神级提示词,涵盖多

    46分钟前
    00
  • 初始JESD204B高速接口协议(JESD204B一)

    01、对比LVDS与JESD204JESD204B是逻辑器件和高速ADCDAC通信的一个串行接口协议,在此之前,ADCDAC与逻辑器件交互的接口大致分为如下几种。低速串行接口(I2C、SPI)、低速并行接口(包含时钟信号和并行数据信号,

    45分钟前
    00
  • 面试官:从三万英尺角度谈一下Ceph架构设计(1)

    把面试官当陪练,在找工作中才会越战越勇大家好我是小义同学,这是大厂面试拆解——项目实战系列的第3篇文章,如果有误,请指正。本文主要解决的一个问题,Ceph为例子 如何描述项目的架构。一句话描述:主要矛盾发生变化10年前的技术和方案,放到10

    38分钟前
    00
  • 如何打造高效AI智能体?

    作者|Barry Zhang, Anthropic地址|出品|码个蛋(ID:codeegg)整理|陈宇明最近看到了 Anthropic 那篇著名的《Building effective agents》作者之一 Barry Zhang 在 2

    36分钟前
    00
  • 非nvidia卡torchvision报错修复: operator torchvision::nms does not exist

    在Ascend 910b上安装vllm, 会自动把torchaudio和torchvision安装上去.安装前代码语言:shell复制pip list | grep torchtorch

    35分钟前
    00
  • OWASP TOP10

    什么是OWASP?它的全称是 Open Web Application Security Project(开放式 Web 应用程序 安全 项目)TOP 10OWASP Top 10的意思就是10项最严重的Web 应用程序安全风险列表 ,它总

    27分钟前
    00
  • Prometheus配置docker采集器

    Prometheus 配置 Docker 采集器Prometheus 是一个开源的监控系统和时间序列数据库,广泛用于容器化环境中。通过监控 Docker 容器,用户可以实时获取服务性能、资源使用情况等信息。本文将介绍如何为 Docker 容

    24分钟前
    00
  • 开源在线考试系统

    看到调问已经开始扩展在线考试的场景,试了一下,发现在线考试的基本能力都已经支持了。主要是考试中的各种计分功能,包括对每道题的选项设置分值计算、考试时间限制等,和官方了解了一下,考试中的其他各项能力也在逐步完善,有需求可以随时

    20分钟前
    00
  • Power BI 无公式实现帕累托图表

    帕累托分析(Pareto Analysis),也被称为8020法则、关键少数法则,是一种常用的管理工具,用于识别和处理影响业务的主要因素。看到李伟坚老师在Excel使用Vega实现了花式帕累托(参考:Excel 零公式实现高级帕累托图表)

    19分钟前
    00
  • CUT&amp;amp;Tag 数据处理和分析教程(7)

    过滤某些项目可能需要对比对质量分数进行更严格的过滤。本文细讨论了bowtie如何分配质量分数,并举例说明。MAPQ(x) = -10 * log10log10(P(x is mapped wrongly)) = -10 * log10(p)

    12分钟前
    10
  • 什么是docker?它是如何工作的?

    想象一个场景,你要部署一个服务,然后它对环境有很多依赖,不同的操作系统又是不同的需求,而且还可能遇到有些源不能使用,又得一番折腾,折腾完上线后,假设要在新的环境再来一套,又得再来一遍。那么有没有什么办法可以解决呢?有办法,docker就是干

    9分钟前
    00
  • module &#x27;torch.

    踩坑Ascend, 安装 pytorch 2.5.1 和 pytorch_npu 2.5.1, import torch 报错.执行 python -c "import torch;import torch_npu;"时

    4分钟前
    10
  • 大模型驱动金融数据应用的实战探索

    近年来,人工智能技术的飞速发展正在重塑全球各行各业的生态格局,金融行业作为数据密集型领域,更是首当其冲。大模型凭借其强大的自然语言处理、逻辑推理和生成能力,逐渐成为金融数据应用的核心驱动力。本文将从行业背景与趋势、核心场景重构、产品能力提升

    1分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信