node ninja
node ninja

Reputation: 33056

Setting innerHTML vs. setting value with Javascript

When you want to use Javascript to change HTML, how do you know when to use either of the following?

document.getElementById("randomNumber").value = number;
document.getElementById("randomNumber").innerHTML = number;

Upvotes: 44

Views: 52577

Answers (8)

mordi
mordi

Reputation: 86

It's a little late for him but I was also looking for an answer and I think according to Skyrim answer It is possible to do something like this Thanks

function enterValue() {
  var childNodes = document.body.childNodes;
  for (x of childNodes) {
    if(x.nodeName=="INPUT"){
      // element is an INPUT html tag
      x.value = "my input value";
    }else{
      // element is anything other than an INPUT
      x.innerHTML  = "my input value";
    }
  }
}
<!DOCTYPE html>
<html>
<body>
<input name="mInput" />
<div></div>
<p id="demo"></p>

<input type="button" onclick="enterValue()" value="enterValue">
</body>
</html>

Upvotes: 1

Skyrim
Skyrim

Reputation: 865

value is generally a property of specific i/o elements such as input elements (also including the type="hidden").

elements which are not such as div, p, a, etc. generally don't even have the value property and even if a value is set, does not affect the final output.

Upvotes: 8

bballer320xu
bballer320xu

Reputation: 35

Use .innerHTML to replace the entire inner body of the element with valid HTML you specify. A good example of this would be to place a nested div in an already existing div if an event occurs.

Use .value for form elements that request a value, such as a text input.

Upvotes: 0

jjmontes
jjmontes

Reputation: 26974

value applies only to objects that have the value attribute (normally, form controls).

innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).

They are not equivalent or replaceable. Depends on what you are trying to achieve...

Upvotes: 3

Jay Tomten
Jay Tomten

Reputation: 1717

Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.

Here is a link showing the use of ID.value: http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml

Upvotes: 49

ThiefMaster
ThiefMaster

Reputation: 318778

value is for form elements, innerHTML if you want to set the content of any other element.
There's also innerText if you want to set the text content (you won't have to escape anything in there, but no HTML works in there)

Upvotes: 15

Daniel A. White
Daniel A. White

Reputation: 191058

value represents the value that would be GETed or POSTed for input elements. innerHTML could change the contents actual elements.

Upvotes: 2

JuSchz
JuSchz

Reputation: 1208

Value is for input

innerHTML for div and span

Upvotes: 1

Related Questions