Get Content - text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
text() and html() methods:
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script>
Example(2) For getting the value of an input field with the jQuery val() method:
<script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
});
</script>
Get Attributes - attr()
The jQuery attr() method is used to get attribute values.
The following example demonstrates how to get the value of the href attribute in a link:
<script>
$(document).ready(function(){
$("#link").click(function(){
alert($("#linK_name").attr("href"));
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>How To Get Content and Attributes In JQuery With Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
body {
background: darkolivegreen;
}
</style>
<body>
<div class="container">
<br><br><br>
<div class="text-center">
<h2 id="color" style="color: White">Get Content and Attributes In JQuery </h2>
</div>
<br>
<br>
<div class="well">
<p><a href="https://blog.bajarangisoft.com/blogs" id="linK_name">Bajarangisoft.com</a></p>
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button class="btn btn-info" id="btn1">Set Text</button>
<button class="btn btn-info" id="btn2">Set HTML</button>
<button class="btn btn-info" id="btn3">Set Value</button>
<button id="show_value" class="btn btn-info">Show Value</button>
<button id="link" class="btn btn-info">Show href Value</button>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
$("#show_value").click(function(){
alert("Value: " + $("#test").val());
});
$("#link").click(function(){
alert($("#linK_name").attr("href"));
});
});
</script>