jQuery Get Content
One of the most common things you will do with jQuery is read what is already sitting inside your page. jQuery gives you three friendly methods for this: text(), html(), and val(). Once you understand the difference between them, pulling data out of any element becomes second nature.
Reading content the jQuery way
When you call one of these methods without passing any argument, jQuery works in "get" mode. That means it returns the current value from the element instead of changing it. This is the key idea to remember: the same method name is used for both reading and writing, and the difference is simply whether you hand it a value or not.
- text() returns the combined text of the selected element and its children, with all HTML tags stripped out.
- html() returns the inner HTML, so any tags inside the element come back as part of the string.
- val() returns the current value of form fields such as input, textarea, and select.
Getting text and HTML
Imagine a paragraph that contains a bold word inside it. Calling text() gives you just the readable words, while html() gives you the words plus the surrounding markup. Try clicking each button below to see the two results side by side.
text() versus html()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="demo">Hello <b>world</b>!</p>
<button id="getText">Get Text</button>
<button id="getHtml">Get HTML</button>
<script>
$(document).ready(function() {
$("#getText").click(function() {
// Returns: Hello world!
alert($("#demo").text());
});
$("#getHtml").click(function() {
// Returns: Hello <b>world</b>!
alert($("#demo").html());
});
});
</script>
</body>
</html>Getting values from form fields
Text and html do not work for reading what a user typed into an input box. For form controls you reach for val(), which returns whatever is currently entered or selected. This is how you grab data before validating a form or sending it to a server.
Reading an input with val()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input type="text" id="username" value="kishore">
<button id="show">Show name</button>
<script>
$(document).ready(function() {
$("#show").click(function() {
var name = $("#username").val();
alert("You entered: " + name);
});
});
</script>
</body>
</html>With these three methods you can pull almost any piece of content out of your page. In the next lesson you will use the very same methods to change that content instead of just reading it.
Exercise: jQuery Get Content
What does $("p").text() return when called with no arguments on multiple paragraphs?