In this example I will show you how to add class and remove class using javascript. It can be achieved by using ClassName property. We can get all elements in the document with the specified tag name.
Here I passed TR tag to the method getElementByTagName () and it will returns collection of all elements with specified tag element as object. With the help of object length by looping we can identify the class name and replace it.
Example:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnChange").click(function () {
var tr = document.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
if (tr[i].className === 'highlight') {
tr[i].className = 'normal';
}
}
});
});
</script>
<style type="text/css">
td {
border-bottom:1px solid #808080;
}
.highlight {
background-color: #2a78ac;
color:white;
}
.normal {
background-color: #FFFCC9;
}
</style>
</head>
<body style="font-family: Arial; width: 500px;border:1px solid #e5dddd">
<table>
<tr class="highlight">
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
</tr>
<tr class="highlight">
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>42</td>
</tr>
<tr >
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
</tr>
</table>
<button id="btnChange" >change</button>
</body>
</html>
Output:
But in jQuery it is very easy with single line of code. It reduces the large amount of code.
$("tr.highlight").removeClass("highlight").addClass("normal");
Post your comments / questions
Recent Article
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article