Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add and remove HTML attributes with jQuery?
To add and remove HTML attributes with jQuery, you can use several methods. The addClass() and removeClass() methods work specifically with CSS classes, while attr() and removeAttr() methods handle general HTML attributes.
Adding and Removing CSS Classes
The addClass() method adds one or more CSS classes to selected elements, while removeClass() removes them. This is the most common way to dynamically modify element styling.
Example
You can try to run the following code to add and remove CSS classes with jQuery ?
<!DOCTYPE html>
<html>
<head>
<title>jQuery Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add').click(function() {
$('#page_navigation1').addClass('blue-class');
});
$('#remove').click(function() {
$('#page_navigation1').removeClass('blue-class');
});
});
</script>
<style>
.blue-class {
background-color: blue;
font-size: 30px;
color: white;
padding: 10px;
}
</style>
</head>
<body>
<div id="page_navigation1">Demo Text</div>
<button id="add">Add Class</button>
<button id="remove">Remove Class</button>
</body>
</html>
Adding and Removing General Attributes
For other HTML attributes like id, src, href, or custom data attributes, use the attr() method to add or modify attributes and removeAttr() to remove them completely.
Example
Here's how to work with general HTML attributes ?
// Add or modify attributes
$('#myElement').attr('title', 'New tooltip text');
$('#myImage').attr('src', 'new-image.jpg');
// Remove attributes
$('#myElement').removeAttr('title');
$('#myLink').removeAttr('href');
Conclusion
jQuery provides flexible methods for manipulating HTML attributes: use addClass()/removeClass() for CSS classes and attr()/removeAttr() for general attributes, making dynamic content modification simple and efficient.
