Using JQuery Add A New Class To An Element That Already Has A Class
Maybe your like
jQuery Fundamental - I : Exercise-7
Using jQuery add a new class to an element that already has a class.
Add the "w3r_bg_blue" class to a paragraph that already has a "w3r_bg_orange" class
<p class="w3r_bg_orange">The best way we learn anything is by practice and exercise questions.</p> p { background: white; } .w3r_bg_orange{ background: orange; } .w3r_bg_red { color: red; }Sample solution :
HTML Code :
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-git.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <p class="w3r_bg_orange">The best way we learn anything is by practice and exercise questions.</p> <button id="button1">Click to see the effect</button> </body> </html>CSS Code:
button { display: block; margin: 20px 0 0 0; } p { background: white; } .w3r_bg_orange{ background: orange; } .w3r_bg_red { color: red; }JavaScript Code :
$('#button1').click(function(){ $( "p" ).addClass(function( index, currentClass ) { var addedClass; if ( currentClass === "w3r_bg_orange" ) { addedClass = "w3r_bg_red"; } return addedClass; }); });Used Methods :
- .addClass() : Adds the specified class(es) to each element in the set of matched elements
Go to:
- jQuery Fundamental-I Exercises Home ↩
- jQuery Exercises Home ↩
PREV : Using jQuery add the class "w3r_font_color" and “w3r_background” to the last paragraph element. NEXT : Using jQuery insert some HTML after all paragraphs.
See the Pen jquery-fundamental-exercise-7 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Tag » Add Class To Id Element Jquery
-
Jquery Add Class To Element By Id Code Example - Code Grepper
-
.addClass() | JQuery API Documentation
-
JQuery AddClass() Method - W3Schools
-
JQuery Find #ID, RemoveClass And AddClass - Stack Overflow
-
Using JQuery To Add Class To HTML Element
-
JQuery AddClass() Method Tutorial - YogiHosting
-
Add Class To Clicked Element Using JavaScript - Bobbyhadz
-
How To Add / Remove CSS Class Dynamically In JQuery
-
JQuery Add And Remove CSS Classes - Tutorial Republic
-
JavaScript Adding A Class Name To The Element - GeeksforGeeks
-
JQuery AddClass With HTML Table, Button, Links And List Demos
-
JQuery Selectors Explained: Class Selectors, ID Selectors, And More
-
Lesson 1: Understanding ID And Class In CSS
-
Target Elements By Class Using JQuery - Snakify