We will check how attributes and properties work in JQuery.
In the web we can see an input with id example and an element a with id my_link with a link.
xxxxxxxxxx
<html>
<body>
<input id="example"><br>
<a href="https://www.lookkle.com" id="my_link">Link</a>
<br><br>
<!--Script jQuery-->
<script>
$(document).ready(function(){
//Saving in a url variable the value of the attribute
var url = $("#my_link").attr("href");
console.log('My link is '+url);
//Set the a attribute to target="_blank"
$("#my_link").attr("target","_blank");
//Apply for id example the attributes type text and value Mike
$("#example").attr({
type:"text",
value:"Mike"
});
console.log('Attribute value is');
console.log($("#example").attr("value"));
console.log('Property value is');
console.log($("#example").prop("value"));
console.log('Attribute type is');
console.log($("#example").attr("type"));
console.log('Property type is');
console.log($("#example").prop("type"));
//Changing the attribute value to John
$("#example").attr('value',"John");
console.log('Changed Attribute is ');
console.log($("#example").attr("value"));
console.log('Changed property is');
console.log($("#example").prop("value"));
//Changing its value to Nothing with val()
$("#example").val("Nothing");
console.log('Changed Attribute with val() is ');
console.log($("#example").attr("value"));
console.log('Changed property with val() is');
console.log($("#example").prop("value"));
});
</script>
<!--JQuery Library-->
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</body>
Interesting Articles