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

如何为div元素设置自定义value属性并完成赋值操作?

解决方案

你直接操作.value属于给DOM元素的JS对象新增自定义属性,不会同步到HTML标签的属性节点上,因此无法通过getAttribute读取。如果要修改标签上的value属性,直接使用setAttribute方法即可:

document.getElementById('div').setAttribute('value', 2)

拓展建议

如果没有强制要使用value作为属性名的要求,更推荐使用符合HTML规范的data-*自定义属性方案,使用更便捷:

  1. 标签定义改为:
<div id="div" data-value="1">
  1. 赋值语法:
document.getElementById('div').dataset.value = 2
  1. 取值语法:
// 两种方式都可以读取
const val = document.getElementById('div').dataset.value
// 或者
const val = document.getElementById('div').getAttribute('data-value')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:36:02