DOM एलिमेंट में क्लास जोड़ने के लिए, पहले आपको उसे querySelector, getElementById आदि का उपयोग करके ढूंढना होगा। फिर क्लास जोड़ें।
उदाहरण HTML
<!DOCTYPE html>
<html>
<head></head>
<body>
<p id="para">यह कुछ टेक्स्ट है</p>
</body>
</html>
एलिमेंट ढूंढना
querySelector (आधुनिक, लचीला)
let myPara = document.querySelector('#para');
getElementById (तेज, केवल ID के लिए)
let myPara = document.getElementById('para');
क्लास जोड़ना
let myPara = document.getElementById('para');
myPara.classList.add('myClass');
व्यावहारिक उदाहरण
// फॉर्म वैलिडेशन फीडबैक
function showError(inputId, message) {
const input = document.getElementById(inputId);
input.classList.add('error');
input.setAttribute('aria-invalid', 'true');
// एरर मैसेज एलिमेंट बनाएं/अपडेट करें
let errorEl = input.parentNode.querySelector('.error-message');
if (!errorEl) {
errorEl = document.createElement('span');
errorEl.className = 'error-message';
input.parentNode.appendChild(errorEl);
}
errorEl.textContent = message;
}
function clearError(inputId) {
const input = document.getElementById(inputId);
input.classList.remove('error');
input.removeAttribute('aria-invalid');
const errorEl = input.parentNode.querySelector('.error-message');
if (errorEl) errorEl.remove();
}
CSS के साथ संयोजन
.error {
border-color: #dc3545;
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}
.error:focus {
outline: none;
border-color: #dc3545;
}