You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JS(无jQuery)点击按钮获取同div下相邻p标签innerText

问题场景

页面包含多个卡片盒子,每个盒子内有1个按钮和1个<p>元素,<p>的文本由API返回数据动态生成。目前已为同时包裹<p>和按钮、类名为shape-box的父级<div>绑定onclick事件,需要实现点击按钮时,在控制台输出同个div下与按钮相邻的<p>标签的innerText。

现有代码

JavaScript 逻辑

const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
    .then(res => res.json())
    .then(data => data.results.map(item => {
        return containerShapes.innerHTML +=
         `<div class="shape-box" onclick="showName(event)">
            <p>${item.name}</p>
            <button>Select</button>
          </div>`
    }))

function showName(e) {
    console.log()
}

样式代码

#container-pock-shape {
    display: flex;
    flex-wrap: wrap;
}

.shape-box {
    border: 2px solid red;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;
    width: 200px;
}
    
.shape-box p {
    background-color: grey;
    width: 100px;
    text-align: center;
    font-weight: 900;
}

HTML 结构

<body>
  <div id="container-pock-shape">
  </div>
</body>
实现方法

直接补全showName函数逻辑即可,通过事件对象定位到当前卡片容器,再查找内部的<p>标签取值:

function showName(e) {
  // 过滤非按钮的点击,仅点击Select按钮时执行
  if (e.target.tagName !== 'BUTTON') return
  // 向上查找最近的.shape-box父容器
  const currentBox = e.target.closest('.shape-box')
  // 读取容器内p标签的文本并打印
  console.log(currentBox.querySelector('p').innerText)
}

逻辑说明

  • e.target指向实际触发点击事件的元素,通过判断标签名可以保证只有点击按钮时才执行打印逻辑
  • closest()方法会沿DOM树向上查找匹配指定选择器的最近祖先元素,适配动态渲染的DOM结构
  • 拿到父容器后通过querySelector('p')直接定位内部的p标签,不需要手动处理相邻元素的遍历逻辑,兼容性更好

内容的提问来源于stack exchange,提问作者Romi Tsimerman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 12:12:10