Search code examples
javascripthtmlattributessetvaluegetattribute

How could I set the value of a div?


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!


Solution

  • 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.