Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ".innerHTML" and ".value" in JS

Tags:

javascript

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?

like image 416
Jun Q Avatar asked Jul 04 '15 23:07

Jun Q


People also ask

What is difference in innerHTML and innerText?

innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.

Why do we use .innerHTML in JavaScript?

The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.

What is the difference between textContent and innerText?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.

What is the difference between innerHTML and appendChild?

Answer : appendChild is used to insert new node in DOM. innerHTML is a property of DOM that allows to replace content of an element with different HTML, which automatically gets parsed into DOM nodes.


1 Answers

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.'
like image 148
jax Avatar answered Oct 13 '22 00:10

jax