Codelab Editor
Free Online HTML Editor
Run
Learn jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery attr() Example – Update Attributes Using Callback</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <style> body { font-family: sans-serif; padding: 30px; background: #f9f9f9; } .highlight { color: white; background: teal; padding: 10px; } button { padding: 8px 15px; margin-top: 20px; background: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; } table { margin-top: 30px; border-collapse: collapse; width: 100%; max-width: 600px; background: #fff; border: 1px solid #ccc; } th, td { padding: 10px; border: 1px solid #ccc; text-align: left; } th { background-color: #f1f1f1; } </style> </head> <body> <h2 id="mainTitle" class="heading">Original Heading</h2> <button id="setAttrBtn">Update ID and Class</button> <table> <tr> <th>Attribute</th> <th>Old Value</th> <th>New Value</th> </tr> <tr> <td>ID</td> <td id="oldId"></td> <td id="newId"></td> </tr> <tr> <td>Class</td> <td id="oldClass"></td> <td id="newClass"></td> </tr> </table> <script> $(document).ready(function(){ const $title = $('#mainTitle'); // Display initial values $('#oldId').text($title.attr('id')); $('#oldClass').text($title.attr('class')); $('#setAttrBtn').click(function(){ // Update attributes using callback $title.attr('id', function(i, val){ return val + '_updated'; }); $title.attr('class', function(i, val){ return val + ' highlight'; }); // Update table values $('#newId').text($title.attr('id')); $('#newClass').text($title.attr('class')); }); }); </script> </body> </html>
Editor Commands
Ctrl
F
Find
Ctrl
G
Find Next
Ctrl
⇧
G
Find Previous
Ctrl
⇧
F
Find & Replace
Ctrl
]
Indent Code Right
Ctrl
[
Indent Code Left
⇧
Tab
Auto Indent Code
Ctrl
/
Line Comment
Ctrl
Alt
/
Block Comment
TutsInsider Actions
Alt
S
Run Code
Ctrl
C
Copy Editor Code
Ctrl
A
Select All Editor Code
Ctrl
S
Save/Download
Ctrl
Alt
X
Rotate
Ctrl
Alt
T
Switch Theme
Ctrl
⇧
C
Open Console
Esc
Close Console