David
David

Reputation: 57

Adding "value" to div

My problem is about DIV attributes in JavaScript.
DIV cannot have value attribute, but I need to make it have some "value" to hold the i variable.
Here's an example of what I have:

for (i = 1; i <= endDate; i++) {
  if (i === today.getDate() && dt.getMonth() === today.getMonth() && dt.getFullYear() === today.getFullYear()) {
    cells += "<div class='today'>" + i + "</div>";
  } else {
    cells += "<div onclick='dayChanger()' value='i'> " + i + "</div>";
  }
}

function dayChanger(obj) {
  dt.setDate(obj.value);
}

Upvotes: 1

Views: 4790

Answers (1)

Jeroen Bourgois
Jeroen Bourgois

Reputation: 180

Well a div can have a value attribute, but it is less common. You should just use data-* attributes.

For example: <div ... data-value='i'>.

Then in your handler, you can access it like to:

obj.getAttribute("data-value")

// or, if you are not targeting dinosaur browsers:

obj.dataset.value

Also, you might consider building the div as an element instead of interpolating, but that is just personal taste. For this small example, it is fine.

Upvotes: 2

Related Questions