January 04, 2025
How to change HTML attributes using jQuery
We can use jQuery to change HTML attributes of an HTML elements. There is attr method available for this purpose. The attr function allows us to change any HTML attribute of a selected element. Example is mentioned below:
attr method example
<html>
<head>
<title>Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="textElem" value="Sample Text">
<button id="btnGetAttr">Get Value Attribute</button>
<button id="btnSetAttr">Set Value Attribute</button>
<button id="btnRemoveAttr">Remove Value Attribute</button>
<script>
$(document).ready(function () {
$('#btnSetAttr').on('click', function () {
$("#textElem").attr({'value':'Programming World'});
});
$('#btnGetAttr').on('click', function () {
alert($("#textElem").attr('value'));
});
$('#btnRemoveAttr').on('click', function () {
$("#textElem").removeAttr('value');
});
});
</script>
</body>
</html>