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

如何获取当前脚本所在元素的ID?

如何获取当前脚本所在元素的ID?

嘿,这个需求我太懂了——不想硬编码父元素的ID,想让脚本自己“感知”到它所在的容器,对吧?其实用document.currentScript就能轻松搞定!

这个API会精准返回当前正在执行的<script>元素本身,然后我们只需要取它的直接父元素(也就是你那个带someId的div),就能拿到对应的ID了,完全不用提前写死ID值。

直接给你修改好的完整代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DIV Test</title>
    <style>
        div.someClass { background-color: cyan; }
    </style>
</head>
<body>
    <h1>DIV Test</h1>
    <div class="someClass" id="someId">
        <p>Original text.</p>
        <script>
            // 核心逻辑就在这里
            const currentScriptTag = document.currentScript;
            const parentContainer = currentScriptTag.parentElement;
            const containerId = parentContainer.id; // 这里就拿到了"someId"

            console.log(containerId); // 可以打印出来验证结果
            parentContainer.insertAdjacentHTML("beforeend", "<p>Some other text</p>");
        </script>
    </div>
</body>
</html>

我给你拆解下关键步骤:

  • document.currentScript:这是关键,它能准确找到当前正在运行的这个脚本标签,不会和页面里其他脚本搞混
  • 调用currentScriptTag.parentElement:直接获取到这个脚本的父容器,也就是你要找的那个div
  • 最后通过parentContainer.id就能拿到容器的ID,完美替代硬编码的document.getElementById("someId")

要是你担心老浏览器的兼容性(比如IE),其实还有个备选方案:给当前脚本标签加个独特的类名或者属性,然后用document.querySelector定位到它,但现在主流浏览器都支持document.currentScript,这个方法足够日常使用啦。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 06:58:08