Profe
Profe

Reputation: 1

Changing value by id issue

I am trying to change the value of data-value for the following piece of code:

<div class="media-body">
    <small>Total MA'ers found</small>
    <h2 id="totalma" class="media-heading animate-number" value="29" data-animation-duration="1500">0</h2>
</div>

I have tried:

document.getElementById('totalma').data-value = 90;

Which returns the error: ReferenceError: invalid assignment left-hand side

Upvotes: 0

Views: 55

Answers (3)

Alnitak
Alnitak

Reputation: 339917

.data-value isn't a legal JavaScript property name because of the hyphen, and in any event user specified DOM attributes aren't automatically mirrored into properties.

The correct method is therefore:

 document.getElementById('totalma').setAttribute('value', 90);

[An <input> element's value attribute and .value property are mirrored, but in this case you're using an <h2> element which has no such attribute / property].

If however, you actually meant to use the HTML5 attribute data-value then correct usage would be:

document.getElementById('totalma').dataset.value = 90;

Upvotes: 1

amiramw
amiramw

Reputation: 506

Use setAttribute instead:

document.getElementById('totalma').setAttribute("value", 90);

Upvotes: 0

quirimmo
quirimmo

Reputation: 9988

Try changing this:

document.getElementById('totalma').data-value = 90;

to this (if you want to change value attribute):

document.getElementById('totalma').setAttribute('value', 90);

to this (if you want to change/set data-value attribute):

document.getElementById('totalma').setAttribute('data-value', 90);

Upvotes: 6

Related Questions