1

Why is this line of JS code returning the error "cannot set property ... of undefined"?

document.forms["myForm"]["english_error"].textContent = "English sentence is required";

I am referencing the id of my div element correctly.

<input type="text" id="english" name="english" placeholder="English sentence" />
<div id="english_error" class="val_error"></div>
2
  • 2
    Assuming those elements are in myForm, not all elements with an ID will show up as properties of the form element. Mainly form controls will. Commented Nov 18, 2016 at 21:48
  • 1
    Possible duplicate of How to reference ID of DIV sending JavaScript call? Commented Nov 18, 2016 at 21:56

1 Answer 1

1

Only form controls are mapped, basically only <input>, <textarea>, <select> tags:

var sentence = document.forms["myForm"]["english"];

Is an <input> tag so this works:

document.forms["myForm"]["english_error"].textContent = "English sentence is required";

english_error is normal <div> so doesn't work, you have to use:

document.getElementById("english_error").textContent = "English sentence is required";

And also by class name:

document.getElementsByClassName("val_error")[0].textContent = "English sentence is required";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.