Working with HTML Attributes
While native JavaScript uses element.attributeName or element.setAttribute() to manage element attributes, jQuery provides the attr() and removeAttr() metthods for more steramlined operations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Attribute Example</title>
<style>
.highlighted {
background-color: lightblue;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function getAttributes() {
let sampleElement = $('#sampleText');
console.log('Color:', sampleElement.attr('color'));
console.log('ID:', sampleElement.attr('id'));
console.log('Size:', sampleElement.attr('size'));
}
function modifyAttributes() {
$('#sampleText').attr('color', 'blue');
$('#sampleText').attr('size', '6');
}
function deleteAttribute() {
$('#sampleText').removeAttr('color');
}
function applyClass() {
$('#sampleText').attr('class', 'highlighted');
}
</script>
</head>
<body>
<font id="sampleText" color="red" size="7">Sample Text</font>
<hr>
<button onclick="getAttributes()">Get Attributes</button>
<button onclick="modifyAttributes()">Change Attributes</button>
<button onclick="deleteAttribute()">Remove Color</button>
<button onclick="applyClass()">Apply Class</button>
</body>
</html>
Managing CSS Styles
Native JavaScript modifies styles using element.style.propertyName = 'value'. jQuery simplifies this with the css() method. For clas-based styling, jQuery offers dedicated methods: addClass(), removeClass(), and toggleClass().
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Style Example</title>
<style>
.baseBox {
width: 150px;
height: 150px;
background-color: lightcoral;
}
.borderEffect {
border: 8px solid darkgreen;
border-radius: 15px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function changeStyles() {
let box = $('#boxOne');
console.log('Width:', box.css('width'));
console.log('Height:', box.css('height'));
console.log('Background:', box.css('background-color'));
box.css('width', '250px');
box.css('height', '200px');
box.css('background-color', 'lightyellow');
}
function attachClass() {
$('#boxTwo').addClass('borderEffect');
}
function detachClass() {
$('#boxTwo').removeClass('borderEffect');
}
function switchClass() {
$('#boxTwo').toggleClass('borderEffect');
}
</script>
</head>
<body>
<div id="boxOne" class="baseBox"></div>
<button onclick="changeStyles()">Adjust Styles</button>
<div id="boxTwo" class="baseBox">
Content
</div>
<button onclick="attachClass()">Add Class</button>
<button onclick="detachClass()">Remove Class</button>
<button onclick="switchClass()">Toggle Class</button>
</body>
</html>