Good guidance about when to use .value and when to use .innerHtml

FYI:https://stackoverflow.com/questions/8823498/setting-innerhtml-vs-setting-value-with-javascript

Not having this info cost me me almost two hours last night.

Is this a question, or something that other members might find of use?

Yes.

I guess that clears that up then…

3 Likes

Please excuse me. Brain fart!

Yes, I think the link is something other members might find useful.

2 Likes

Hm well I don’t think that answers like the top-rated one – Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements. – are particularly helpful… there are actually pretty hard and fast rules when to use which. :~)

  • .innerHTML sets the children of an element, generated from a HTML string; it creates and appends (or reads and serializes) DOM nodes. And since input elements can’t have any children (which is also why there’s no closing </input> tag), you can’t set their .innerHTML.
  • .value OTOH holds some (user-) data. It doesn’t reflect the content of the page, but a certain state – typically the result of some user interaction. This state is what is getting sent to the backend when you submit a form, say; and since you wouldn’t send your own content back to the server, elements like divs don’t have .values.

Now consider a button element: it has both an .innerHTML and a .value property. The former is what is getting rendered inside the button, while the latter tells you about the action of the user (e.g. inside a click-handler).

2 Likes

To play devil’s advocate, there’s also
textContent or in jQuery text

IMHO there’s no need to use innerHTML unless you’re placing DOM elements.

2 Likes

When you want to receive the value of a specific field in the JavaScript function, in such situation you can use .value and get the value of a specific division.
When you want to send back the value into the HTML text box then you can use the .innerHTML. This is usually used after performing addition or some specific operation and then to show the answer in the text box, .innerHTML is really quick to use!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.