Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> JavaScript

जावास्क्रिप्ट का उपयोग करके किसी दिए गए एलिमेंट में क्लास कैसे जोड़ें?

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;
}
  1. JavaScript से एलिमेंट से क्लास नाम कैसे हटाएं? JavaScript से एलिमेंट से क्लास नाम कैसे हटाएं?

    JavaScript से एलिमेंट से क्लास नाम हटाने के लिए, निम्न कोड का उपयोग करें: उदाहरण <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style>    .newStyle {       font-family: &

  1. JavaScript का उपयोग करके पैरेंट एलिमेंट के चाइल्ड एलिमेंट कैसे प्राप्त करें? JavaScript का उपयोग करके पैरेंट एलिमेंट के चाइल्ड एलिमेंट कैसे प्राप्त करें?

    JavaScript का उपयोग करके पैरेंट एलिमेंट के चाइल्ड एलिमेंट प्राप्त करने का निम्नलिखिक कोड है:उदाहरण<!DOCTYPE html> <html lang="hi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"

  1. जावास्क्रिप्ट का उपयोग करके पैरेंट एलिमेंट के CSS प्रॉपर्टीज़ को इनहेरिट करना जावास्क्रिप्ट का उपयोग करके पैरेंट एलिमेंट के CSS प्रॉपर्टीज़ को इनहेरिट करना

    आप append() के साथ classList.add() का उपयोग कर सकते हैं। नया डिव बनाने के लिए document.createElement() का उपयोग करें और classList.add() CSS क्लास (.क्लास सेलेक्टर) जोड़ेगा।उदाहरण  Document .add-all-subject { display: grid; height: 100px; width: 100px; grid-template-columns: 2fr 2fr 2fr 2