-3

Everything works fine if I use the attribute "value".

document.getElementById("email").value = "Email already exists."

But when I try to use an attribute that has a hypen "-" on it, it doesn't work anymore

document.getElementById("email").data-error = "Email already exists."

I've tried variations like ['data-error'] or ."data-error" but I can't seem to find the right syntax.

LF00
  • 27,015
  • 29
  • 156
  • 295

2 Answers2

0

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).

In your case, if you want to set a value to data attribute:

document.getElementById("email").dataset.error = "Email already exists."

Source: https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes

James
  • 1,436
  • 1
  • 13
  • 25
0

I guess you are using a text field, value attribute can be accessed in two ways by directly calling

document.getElementById("email").value = "Email already exists."

and by using setAttribute.

document.getElementById("email").setAttribute("value", "value of text field");

so to set an attribute value of data-error we need use it as

document.getElementById("email").setAttribute("data-error", "Email already exists.");

and get the attribute value is by

document.getElementById("email").getAttribute("data-error");
CNKR
  • 568
  • 5
  • 19