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

封装document.querySelector函数时,如何让返回值可直接调用DOM属性与方法?

问题分析与解决方案

你的原函数返回的是字符串形式的代码文本,而非实际执行document.querySelector后得到的DOM元素对象,所以无法直接调用DOM属性和方法。

修改后的函数

直接执行document.querySelector并返回其结果即可:

// 传入参数的值是特定HTML标签的类名。
const docs = (className) => document.querySelector(`.${className}`)

// docs函数中的参数'title'是我的h1标签的类名
const title = docs('title')

// 可选:先判断元素是否存在,避免null报错
if (title) {
  console.log(title)
  title.textContent = 'Hello!';
  title.style.backgroundColor = 'red';
}

关键说明

  • 去掉模板字符串的反引号,直接返回document.querySelector的执行结果,这样得到的是真实的DOM元素对象(或找不到匹配元素时返回null)
  • 增加元素存在性判断是好习惯,避免当目标类名不存在时触发Cannot set properties of null的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:15:36