3

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!

Syscall
  • 19,327
  • 10
  • 37
  • 52
Conmann
  • 33
  • 1
  • 6
  • 2
    `div`'s don't have a value attribute. You can use a [data- attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) to store a value which can then be retrieved. – Rob Moll Oct 14 '21 at 01:03

1 Answers1

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.

Osmar
  • 198
  • 9