使用 document.currentScript 快速获取当前脚本及其兄弟元素
使用 document.currentScript 快速获取当前脚本及其兄弟元素
在现代前端开发中,有时我们需要在内联 <script>
标签中直接操作 DOM 元素。例如,在一个组件化结构中,我们希望基于当前脚本的位置来获取其相邻的 DOM 元素,而无需依赖 id
、class
或全局选择器。
本文将介绍如何使用 document.currentScript
属性快速获取当前正在执行的 <script>
标签,并结合 previousElementSibling
和 nextElementSibling
获取其前一个或后一个兄弟元素。
什么是 document.currentScript
?
document.currentScript
是一个只读属性,它返回当前正在执行的 <script>
元素。这个属性非常适合用于定位当前脚本所在的位置,从而进行后续的 DOM 操作。
const currentScript = document.currentScript;
console.log(currentScript); // 输出当前 <script> 元素
- ✅ 优点:简洁、高效,不需要额外标记。
- 🧩 适用场景:内联脚本、模块化组件、动态插入脚本等需要定位自身位置的情况。
获取当前脚本的上一个兄弟元素
我们可以结合 currentScript.previousElementSibling
来获取当前 <script>
标签的前一个兄弟元素节点(忽略文本节点和注释):
const currentScript = document.currentScript;
const previousElement = currentScript.previousElementSibling;
if (previousElement) {
console.log('上一个兄弟元素:', previousElement);
}
示例 HTML 结构:
<div class="content">我是上一个元素</div>
<script>
const currentScript = document.currentScript;
const previousElement = currentScript.previousElementSibling;
console.log(previousElement); // 输出 div.content
</script>
获取当前脚本的下一个兄弟元素
同理,也可以使用 nextElementSibling
获取当前 <script>
的下一个兄弟元素节点:
const nextElement = currentScript.nextElementSibling;
if (nextElement) {
console.log('下一个兄弟元素:', nextElement);
}
示例 HTML 结构:
<script>
const currentScript = document.currentScript;
const nextElement = currentScript.nextElementSibling;
console.log(nextElement); // 输出 span.description
</script>
<span class="description">我是下一个元素</span>
实际应用示例:为相邻元素添加样式
你可以利用这些方法实现一些实用功能,比如为当前脚本的上一个元素添加背景色:
const currentScript = document.currentScript;
const previousElement = currentScript.previousElementSibling;
if (previousElement) {
previousElement.style.backgroundColor = '#f0f0f0';
}
这在构建文档展示页面、组件说明块、自包含模块时非常有用。
总结
目标 | 方法 |
---|---|
获取当前脚本 | document.currentScript |
获取上一个兄弟元素 | currentScript.previousElementSibling |
获取下一个兄弟元素 | currentScript.nextElementSibling |
通过 document.currentScript
,我们可以轻松地从当前脚本出发访问其周围的 DOM 元素,实现更灵活、更模块化的网页逻辑。这种方法干净、直观,是现代 JavaScript 开发中值得掌握的小技巧。
如果你经常编写组件化脚本或者需要在特定上下文中操作 DOM,不妨试试这个组合拳:currentScript + sibling
,让你的代码更加优雅和可维护!