The attr() method in jQuery is used to sets or returns CSS attributes and values of the selected HTML elements.
This method is like a combination of addClass() and removeClass() methods, it can do multiple replace all classes with one or more new classes.
Syntax:
code:
<!DOCTYPE html>
<html>
<head>
<title>IT PRESENT - jquery attr() method</title>
<style>
.a {
font-family:Impact;
color:blue;
background-color:red;
}
.b {
font-family: Brush Script MT;
color:red;
background-color:green;
}
.c {
font-family: MV Boli;
color:white;
background-color:blue;
}
.d {
font-family: Cambria;
color:yellow;
background-color:maroon;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<p>example replace classes with attr() method</p>
<button id="btn1">BUTTON 1</button>
<button id="btn2">BUTTON 2</button>
<button id="btn3">BUTTON 3</button>
<button id="btn4">BUTTON 4</button>
<script>
$(document).ready(function() {
$("#btn1").click(function() {
$("p").attr("class", "a");
});
$("#btn2").click(function() {
$("p").attr("class", "b");
});
$("#btn3").click(function() {
$("p").attr("class", "c");
});
$("#btn4").click(function() {
$("p").attr("class", "d");
});
});
</script>
</body>
</html>
result: