Getting and Setting Text HTML and Values
Reading Text
The text() method reads back the plain-text content of an element, stripping out any HTML tags found inside it -- so a <strong> tag inside the element is invisible to text(), only its wording is returned.
Example: Reading Text
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><strong>Bold</strong> text</div>
<script>
console.log($("#box").text());
</script>
</body>
</html>
Setting Text
Calling text() with a string argument replaces an element's entire content with that plain text, automatically escaping any HTML-special characters so they display literally rather than being parsed as markup.
Example: Setting Text
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"></div>
<script>
$("#box").text("<b>Not bold</b>");
</script>
</body>
</html>
Reading HTML
html() reads back an element's full inner markup, including any nested tags, which is what you want when you need to inspect or copy structured content rather than just its wording.
Example: Reading HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><strong>Bold</strong> text</div>
<script>
console.log($("#box").html());
</script>
</body>
</html>
Setting HTML
Calling html() with a string argument replaces an element's contents with that markup, parsing it as real HTML -- unlike text(), any tags in the string become live elements in the page.
Example: Setting HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"></div>
<script>
$("#box").html("<strong>Now bold</strong>");
</script>
</body>
</html>
Getting and Setting Values
val() reads or sets the current value of a form control like an input, select, or textarea, which is distinct from text() and html() since a form control's displayed value isn't stored as regular element content.
Example: Getting and Setting Values
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="name" type="text" value="Alice">
<script>
console.log($("#name").val());
$("#name").val("Bob");
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: