Changing textContent of element

Viewed 71

I'm making a form for registration and want to show error in another element if the input doesn't match a condition.

//input element
let field = document.getElementById("field").value.trim();
//div for showing error 
let field_error = document.getElementById("field_error").textContent;
if(field.length > 30){
field_error = "Input too long";
}

If I write code like this it doesn't do anything, but if I put like this:

let field_error = document.getElementById("field_error");
if(field.length > 30){
field_error.textContent = "Input too long";    
}

Why can't I just declare a variable field_error with .textContent, as I did with field and .value.trim(), instead using .textContent later?

1 Answers

The textContent property actually operates more like a getter/setter, potentially applying a transform on get (eg concatenation of the textContent of every child node).

In your first case field_error is pointing at the result of that get (which is now unrelated to the #field_error element) so making changes won't effect the original object.

Your field value likewise couldn't be set (to update the #field element) because it's a manipulated copy of the value.. not a pointer to the DOM element.

Related