I'm having a trouble putting/updating the value of an element got by class name.
here is my code:
index.html
:
<dl>
<dt class="dt-messages-number">total</dt>
<dd class="dd-messages"></dd>
...
</dl>
main.js
:
...
var parsedRes = JSON.parse(res);
console.log(res.messages); //prints undefined
console.log(parsedRes.messages); //prints 23 ,okay
document.getElementsByClassName('dd-messages')[0].value = '7'; //not working
document.getElementsByClassName('dd-messages')[0].value = 7; //not working
document.getElementsByClassName('dd-messages')[0].value =parsedRes.messages; //not working
last three code lines does not work ,it does not update the value of the description element dd-messages
. Does any one have idea why is that ?
I'm having a trouble putting/updating the value of an element got by class name.
here is my code:
index.html
:
<dl>
<dt class="dt-messages-number">total</dt>
<dd class="dd-messages"></dd>
...
</dl>
main.js
:
...
var parsedRes = JSON.parse(res);
console.log(res.messages); //prints undefined
console.log(parsedRes.messages); //prints 23 ,okay
document.getElementsByClassName('dd-messages')[0].value = '7'; //not working
document.getElementsByClassName('dd-messages')[0].value = 7; //not working
document.getElementsByClassName('dd-messages')[0].value =parsedRes.messages; //not working
last three code lines does not work ,it does not update the value of the description element dd-messages
. Does any one have idea why is that ?
-
1
Form elements have a value attribute. A
dd
is not a form element, and has no value. You probably want to set theinnerHTML
instead. – C3roe Commented Sep 1, 2017 at 11:02 -
1
use
innerText
insteadvalue
– Nemani Commented Sep 1, 2017 at 11:03
4 Answers
Reset to default 3You want to use .innerHTML
instead of .value
.
.value
is a method used for inputs, for a text inside <tags></tags>
use .innerHTML
Documentation: .innerHTML
Use .innerText
OR innerHTML
instead
document.getElementsByClassName('dd-messages')[0].innerText = '7';
<dl>
<dt class="dt-messages-number">total</dt>
<dd class="dd-messages"></dd>
</dl>
for difference between .value
, .innetText
and innerHTML
refer this.
As mentioned above, there is no value
attribute on such DOM elements.
You can use either innerHTML
or innerText
.
If you know your value is safe and contains safe html, you can use innerHTML,
otherwise you should go with innerText.
e = <your element by class name>;
e.innerText = e.textContent = "your text"; <-- does not render html--/>
document.getElementsByClassName('dd-messages')[0].innerHTML = "Hello world"
// OR you can Also Use
var dd = document.getElementsByClassName('dd-messages');
console.log(dd.ClassName = "Hello World")
<dl>
<dt class="dt-messages-number">total</dt>
<dd class="dd-messages"></dd>
...
</dl>