最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How could I set the value of a div? - Stack Overflow

programmeradmin0浏览0评论

I know this is not standard but I want to set the value of a div, like this:

<div id="div" value="1">

document.getElementById('div').value = 2;

to use the value you have to use document.getElementById('div').getAttribute('value') but I cant find any way to set it. thanks in advance!

I know this is not standard but I want to set the value of a div, like this:

<div id="div" value="1">

document.getElementById('div').value = 2;

to use the value you have to use document.getElementById('div').getAttribute('value') but I cant find any way to set it. thanks in advance!

Share Improve this question edited Feb 15, 2022 at 16:38 Syscall 19.8k10 gold badges43 silver badges59 bronze badges asked Oct 14, 2021 at 0:53 ConmannConmann 331 silver badge6 bronze badges 1
  • 2 div's don't have a value attribute. You can use a data- attribute to store a value which can then be retrieved. – Rob Moll Commented Oct 14, 2021 at 1:03
Add a ment  | 

1 Answer 1

Reset to default 4

You can't set a value to a div. Instead you can try to add a data attribute, like this:

<div id="div" data-value="1">

And if you want to access the data-value from javascript, just use

elem.dataset.{data_attribute_name};, in this case: document.getElementById('div').dataset.value;

Note that you can set multiple data attributes to one element, making it much more versatile than using value.

发布评论

评论列表(0)

  1. 暂无评论