Getting Content: text(), html(), val() Methods

Here we take a look at the three common methods used in jQuery for retrieving texts (.text()), HTML snippets (.html()) and values from form elements (.val()).

The .text() function returns the concatenated text contents of all matched elements including their child elements. The .html() function gets the HTML contents of the first element of all the matched elements.

Consider the HTML document below

				
				<!DOCTYPE html>
				<html lang="en">
				<head>
					<meta charset="utf-8"/>
					<title>Title of this Page</title>
				</head>
				<body>
				    <p>A text in a paragraph with some part of it <span>inside a span</span>.</p>
				    <p>And some inside a <p>paragraph of another paragraph</p>.</p>
				</body>
				</html>
				
			

We add the following jQuery code into it

				
				<script type="text/javascript">
					$(document).ready(function(){
						console.log($("p").text()); 
					    console.log($("p").html());
					});
				</script>
				
			

In the above example, $("p").text() combines all text contents of all paragraph elements (and their descendants) and returns A text in a paragraph with some part of it inside a span. And some inside a paragraph of another paragraph. And $("p").html() matches only the first element of all the paragraph elements and returns A text in a paragraph with some part of it <span> inside a span</span>.

The .val() method generally fetches values from form elements like input, select and textarea.

				
				<!DOCTYPE html>
				<html lang="en">
				<head>
					<meta charset="utf-8"/>
					<title>Title of this Page</title>
				</head>
				<body>
					<form action="">
					    <input type="text"/> 
					    <select>
					      <option>R2-D2</option>
					      <option>C-3PO</option>
					      <option>BB-8</option>
					    </select>
					    <textarea rows="2" cols="27">Some text inside a textarea.</textarea>
				    </form>
				</body>
				</html>
				

				<script type="text/javascript">
					$(document).ready(function(){
						console.log($("input").val()); 	 
						console.log($("select").val()); 
						console.log($("textarea").val());    
					});
				</script>
				
			

$("input").val() gives whatever the user types in the input box. $("select").val() returns the value of the selected option. And $("textarea").val() returns the text inside the textarea element.