Difference between “.innerHTML” and “.value” in JS

I am confused on what is the difference between .innerHTML and .value in JavaScript. Here is my code:

<body>
Input string: <input type="text" id="input" />
....
</body>

When I use this code I cannot get the content of input string:

var str=document.getElementById("input").innerHTML;

While I use the following code, it works:

var str=document.getElementById("input").value;

Any one knows what is the difference between them?

Answers:

Answer

value refers to the value of an input element (or textearea)

<input value="hello world">

value would be "hello world" (or any value typed inside)


innerHTML refers to the contents inside an HTML element.

<div>
  <span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.
</div>

innerHTML of the div tag would be the string:

  '<span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.'
Answer

The .innerHTML property refers to the literal HTML markup that is, once assigned, interpreted and incorporated into the DOM (Document Object Model) for the current document. On the other hand, the .value property simply refers to the content of typically an HTML input control, such as a textbox. Not every HTML element supports the input property, whereas most if not all support the innerHTML property.

Answer

.value gives you the currently-set value of a form element (input, select, textarea), whereas .innerHTML builds an HTML string based on the DOM nodes the element contains.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.