
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Class to Element Without addClass Method in jQuery
We can use the .attr() method to add a class to an element. This method can be used to set or get the value of an attribute on an HTML element. To add a class, we first select the element using a jQuery selector, and then call the .attr() method, passing in "class" as the first argument and the class name as the second argument.
Let us first understand what jQuery is. jQuery is a JavaScript library that simplifies HTML document traversing, event handling, and animation. It allows for easy manipulation of the Document Object Model (DOM).
It also provides several shorthand methods for common JavaScript tasks, such as making AJAX requests. It is widely used in web development to create interactive and dynamic user interfaces. It can be easily integrated with other libraries and frameworks.
Approach
In jQuery, you can add a class to an element by using the addClass() method, but you can also use the attr() or prop() method to add a class to an element.
For example ?
$("#element").attr("class", "new-class");
OR
$("#element").prop("class", "new-class");
This will add the class "new-class" to the element with the ID "element".
You can also chain multiple class names together using the += operator
$("#element").attr("class", function(i, origValue){ return origValue + " new-class"; });
Example
Here is a complete example of adding a class "new-class" to an element with the ID "element" without removing any existing classes ?
<!DOCTYPE html> <html> <head> <title>Adding Class</title> </head> <body> <div id="element" class="existing-class">This is an element</div> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script> $(document).ready(function(){ $("#element").attr("class", function(i, origValue){ return origValue + " new-class"; }); }); </script> </body> </html>
In this example, we have an HTML element with the ID "element" and class "existing-class". When the document is ready, we select the element using jQuery's $("#element") selector and use the attr() method to add the class "new-class" to the existing classes on the element.
You can check on browser dev tools the class of the element would be "existing-class new-class".