Reputation: 13300
I'm currently following an HTML+CSS+JS tutorial, and I'm new to these stuff.
I'm super confused with value
and textContent
Here's my experiment:
setter textContent
of an <li>
works ✅
const btn = document.querySelector('.button')
btn.addEventListener('click', (event) => {
event.preventDefault()
document.querySelector('#items').lastElementChild.textContent = 'NEW ITEM NAME'
})
getter textContent
returns empty ❌
getter value
returns with value ✅
setter value
works ✅
setter textContent
does not work ❌
const myForm = document.querySelector('#my-form')
const nameInput = document.querySelector('#name')
myForm.addEventListener('submit', onsubmit)
function onsubmit(event) {
event.preventDefault()
console.log("TEXT CONTENT: " + nameInput.textContent) // empty!
console.log("VALUE: " + nameInput.value) // with value!
console.log("SETTING VALUE....")
nameInput.value = "varrrrrr" // setter works!
console.log("SETTING TEXT CONTENT....")
var delayInMilliseconds = 5000;
setTimeout(function() {
nameInput.textContent = "foooooo" // setter does not work!
console.log("DONE SETTING TEXT CONTENT!")
}, delayInMilliseconds);
}
So question is, how does this happen?
Upvotes: 0
Views: 380
Reputation: 455
From MDN:
textcontent
The textContent property of the Node interface represents the text content of the node and its descendants.
let text = document.getElementById('divA').textContent;
document.getElementById('divA').textContent = 'This text is different!';
<div id="divA">This is <span>some</span> text!</div>
value
But only input elements have a "value". It represent the input data supplied by the user or provided initially by the code. Also, input elements may have a "textContent" property but it will always be empty since they are void elements.
let result = document.getElementById("myText").value;
console.log(result)
let val = document.getElementById("myText").value = "Hello World!";
<input type="text" id="myText" value="My text">
In your case, getter textContent returns empty ❌
and setter textContent does not work ❌
both will not work on the input element as mentioned above.
Upvotes: 2