javascript - 如何在内联脚本所在的位置添加 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>
解决方案
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>
推荐阅读
- crystal-reports - 将 Crystal 报表导出到 TTX
- github - 具有 XHTML 1.0 Strict 的 Github 页面,我可以在没有 Cloudflare 邮件保护的情况下使用吗?
- reactjs - 如何在反应中使用另一个相同的函数类型?
- matlab - 从使用 Octave / Matlab 的方程创建的对象创建 3D 拉伸网格
- angular - ionic cordova build android --prod typescript 错误
- html - Bootsrap 固定和响应式 div 高度
- java - 带有 Whilebreakwithloop 的第一个 java 项目的问题
- php - PHP mail.php 操作在连接到 cloudflare 时打开一个新选项卡
- odoo - 如何从 javascript 获取 odoo 模型?
- mysql - 创建连接配置文件时出现问题