jQuery attr(), text(), html(), and val() Functions
attr() Method
Gets or sets attributes of selected elements.
var href = $("#link").attr("href");
alert("Link href attribute: " + href);
text() Method
Sets or retrieves text content of selected elements.
var text = $("#paragraph").text();
alert("Paragraph text content: " + text);
html() Method
Sets or retrieves HTML content of selected elements.
var html = $("#container").html();
alert("Container HTML content: " + html);
val() Method
Sets or retrieves values of form elements.
var value = $("#inputField").val();
alert("Input field value: " + value);
All in one Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get and Set contents in jQuery</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function(){
$(".btn1").click(function(){
// change attribute values
$("a.mylink").attr("href","https://www.flipkart.com");
$("img.pic").attr("src","bulb-on.jpg");
});
$(".btn2").click(function(){
// get text
var x = $(".mypara").text();
//set text
$(".newpara").text(x);
});
$(".btn3").click(function(){
// get html
var x = $(".mypara").html();
//set html
$(".newpara").html(x);
});
$(".btn4").click(function(){
// get value
var x = $("#input1").val();
//set html
$("#input2").val(x);
});
});
</script>
</head>
<body>
<img src="bulb-off.jpg" class="pic" height="250px" alt="">
<p class="mypara" >
Lorem ipsum dolor sit amet consectetur, adipisicing elit. <br>Possimus
molestiae pariatur quod, distinctio itaque modi molestias dignissimos recusandae
explicabo<br> accusamus inventore aliquid soluta doloribus quo autem praesentium
optio numquam harum. <a href="https://www.amazon.com" class="mylink">Shopping</a>
</p>
<p class="newpara">New paragraph</p>
<input type="text" id="input1" value="My text">
<input type="text" id="input2">
<br><br>
<button class="btn1">Change attribute value</button>
<button class="btn2">copy text</button>
<button class="btn3">copy html</button>
<button class="btn4">copy value</button>
</body>
</html>
Run Code