首页 > 解决方案 > 如何在内联脚本所在的位置添加 DOM 元素

问题描述

如何在脚本的位置添加 DOM 元素?

我知道我可以在某处添加一个带有 ID 的 div 并使用 JS 对其进行操作,但我想使用 WordPress 短代码自动将此脚本粘贴到我的网页上的多个位置。因此,脚本必须知道它的位置,并且能够在脚本标签所在的位置添加一个 DOM 元素。

<div class="example-parent">
    <script>
        var funcThatNeedsADivToAttachOnto = function () {
            //...
        }

        document.addEventListener("DOMContentLoaded", function(event) {
            // Need some code here to add div where this script is locate

            funcThatNeedsADivToAttachOnto();
        });
    </script>
    <!-- Want a new div right about here -->
</div>

标签: javascript

解决方案


document.currentScript将为您提供<script>当前正在运行的标签,因此您可以引用它然后使用insertAdjacentElement

<div class="example-parent">
    <script>
        (() => {
            // Use an IIFE so that the "script" variable does not pollute the global object
            const script = document.currentScript;
            document.addEventListener("DOMContentLoaded", function(event) {
                const newDiv = document.createElement('div');
                newDiv.textContent = 'new div';
                script.insertAdjacentElement('afterend', newDiv);
                console.log(document.querySelector('.example-parent').innerHTML);
            });
        })();
    </script>
    <!-- Want a new div right about here -->
</div>


推荐阅读