Difference between val, html and text in jquery

html()

Obtains the HTML content of the first element in the matched set.
$('#Container').html()

text()

Concatenates all text content of the wrapped elements and returns it as the result of the method. That means this method return all the string which display on our browser.
$('#Container').text()

val()

Returns the value attribute of the first element in the matched set. When the element is a multiselect element, the returned value is an array of all selections. This method only works with control like input, select, button etc. It not works with div, span, p etc.
$('#txtCountry').val()
CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $("#btnClick").click(function () {
        alert("HTML: " + $("#Container").html());
        alert("Text: " + $("#Container").text());
        alert("Value: " + $("#txtCountry").val());
      });
    });
  </script>
</head>
<body>
  <div id="Container">
    <b>Country</b>
    <input type="text" id="txtCountry" value="India" />
  </div>
  <button id="btnClick">Click</button>
</body>
</html>
RESULT

Country

5 comments :