What is Difference Between Prop and Attr in jQuery?

In this blog, I will show you What is Difference Between Prop and Attr in jQuery.

both attr() and prop() are used to get or set the value of specified property of an element attribute, but attr() returns the default value (original position) of the property whereas prop() current value gives (current state).


.attr() changes the attributes for that HTML tag.

.prop() changes the properties for that HTML tag according to the DOM tree.

jQuery .prop() method: This method is used to get the value of a property for the first element in the set of matched elements.

For Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(document).ready(function () {
		$("button").click(function () {
			var $val = $("div");
			$val.prop("font-size", "5px");
			$val.append("Property value = "
			+ $val.prop("font-size"));
		});
	});
</script>
<style>
body {
	text-align: center;
}
button {
        background-color: black;
	border: 1px solid black;
	color: white;
	padding: 15px 30px;
	text-align: center;
	text-decoration: none;
	display: inline-block;
	font-size: 16px;
}
</style>
</head>
<body>
<button>Property</button>
<br>
<div></div>
</body>
</html>

Output:

wp-image

jQuery .attr() method: This method is used to either get the value of an attribute from the first element in the matched set or to set the attribute value on all matched elements.

For Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function () {
		var title = $("h1").attr("title");
		$("#divid").text(title);
	});
</script>
<style>
	body {
	text-align: center;
	}
</style>
</head>
<body>
<div>
<h1 style="color: black;" title="jQuery is a JavaScript library">
    jQuery .attr() method </h1>
<p id="myid">jQuery .attr() method</p>
<div id="divid"></div>
</div>
</body>
</html>

Output:

wp-image

Hope this blog is helpful for you ,Thanks for reading this blog.

What is Difference Between Prop and Attr in jQueryexpoundsofttechsolution

What is Difference Between Prop and Attr in jQuery

d