जावास्क्रिप्ट और HTML

जावास्क्रिप्ट और HTML

यह लेख जावास्क्रिप्ट और HTML को समझाता है।

YouTube Video

javascript-html-dom.html
  1<!DOCTYPE html>
  2<html lang="en">
  3<head>
  4  <meta charset="UTF-8">
  5  <title>JavaScript &amp; HTML</title>
  6  <style>
  7    * {
  8      box-sizing: border-box;
  9    }
 10
 11    body {
 12      margin: 0;
 13      padding: 2em;
 14      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 15      background-color: #f7f9fc;
 16      color: #333;
 17      line-height: 1.6;
 18    }
 19
 20    .container {
 21      max-width: 800px;
 22      margin: 0 auto;
 23      padding: 1em;
 24      background-color: #ffffff;
 25      border: 1px solid #ccc;
 26      border-radius: 10px;
 27      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 28    }
 29
 30    h1, h2 {
 31      font-size: 1.5rem;
 32      color: #007bff;
 33      margin-top: 0.5em;
 34      margin-bottom: 0.5em;
 35      border-left: 5px solid #007bff;
 36      padding-left: 0.6em;
 37      background-color: #e9f2ff;
 38    }
 39
 40    button {
 41      display: block;
 42      margin: 1em auto;
 43      padding: 0.75em 1.5em;
 44      font-size: 1rem;
 45      background-color: #007bff;
 46      color: white;
 47      border: none;
 48      border-radius: 6px;
 49      cursor: pointer;
 50      transition: background-color 0.3s ease;
 51    }
 52
 53    button:hover {
 54      background-color: #0056b3;
 55    }
 56
 57    #output {
 58      margin-top: 1em;
 59      background-color: #1e1e1e;
 60      color: #0f0;
 61      padding: 1em;
 62      border-radius: 8px;
 63      min-height: 200px;
 64      font-family: Consolas, monospace;
 65      font-size: 0.95rem;
 66      overflow-y: auto;
 67      white-space: pre-wrap;
 68    }
 69
 70    .highlight {
 71      outline: 3px solid #ffc107; /* yellow border */
 72      background-color: #fff8e1;  /* soft yellow background */
 73      transition: background-color 0.3s ease, outline 0.3s ease;
 74    }
 75
 76    .active {
 77      background-color: #28a745; /* green background */
 78      color: #fff;
 79      box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
 80      transition: background-color 0.3s ease, box-shadow 0.3s ease;
 81    }
 82  </style>
 83</head>
 84<body>
 85  <div class="container">
 86    <h1>JavaScript Console</h1>
 87    <button id="executeBtn">Execute</button>
 88    <div id="output"></div>
 89  </div>
 90
 91  <div class="container">
 92    <h2>HTML Sample</h2>
 93    <div id="content">Hello, World!</div>
 94    <button id="changeText">Change Text</button>
 95  </div>
 96
 97  <script>
 98    // Override console.log to display messages in the #output element
 99    (function () {
100      const originalLog = console.log;
101      console.log = function (...args) {
102        originalLog.apply(console, args);
103        const output = document.getElementById('output');
104        output.textContent += args.map(String).join(' ') + '\n';
105      };
106    })();
107
108    document.getElementById('executeBtn').addEventListener('click', () => {
109      // Prevent multiple loads
110      if (document.getElementById('externalScript')) return;
111
112      const script = document.createElement('script');
113      script.src = 'javascript-html-dom.js';
114      script.id = 'externalScript';
115      //script.onload = () => console.log('javascript-html-dom.js loaded and executed.');
116      //script.onerror = () => console.log('Failed to load javascript-html-dom.js.');
117      document.body.appendChild(script);
118    });
119  </script>
120</body>
121</html>

जावास्क्रिप्ट में window ऑब्जेक्ट

window ऑब्जेक्ट जावास्क्रिप्ट में ब्राउज़र पर्यावरण का ग्लोबल ऑब्जेक्ट है, जो वेब पेज और ब्राउज़र विंडो से संबंधित फ़ंक्शन और जानकारी प्रदान करता है। window चूंकि ब्राउज़र का ग्लोबल स्कोप है, ब्राउज़र में चल रहा सभी जावास्क्रिप्ट कोड window ऑब्जेक्ट का हिस्सा बन जाता है। window ऑब्जेक्ट ब्राउज़र पर्यावरण में जावास्क्रिप्ट चलाने में एक महत्वपूर्ण भूमिका निभाता है और कई API और प्रॉपर्टीज प्रदान करता है।

window ऑब्जेक्ट की मुख्य विशेषताएँ

प्रॉपर्टीज

 1// Get and display the document's title
 2console.log(`Title: ${window.document.title}`);
 3
 4// Get and display the current URL
 5console.log(`URL: ${window.location.href}`);
 6
 7// Go back to the previous page
 8// Note: this will navigate back in history, so be careful when running it
 9console.log("Navigating back to the previous page...");
10window.history.back();
11
12// Display the browser's user agent
13console.log(`User Agent: ${window.navigator.userAgent}`);
14
15// Display the width and height of the viewport
16console.log(`Viewport Width: ${window.innerWidth}`);
17console.log(`Viewport Height: ${window.innerHeight}`);
  • window.document: वर्तमान HTML दस्तावेज़ तक पहुंचता है।
  • window.location: वर्तमान URL और ब्राउज़र नेविगेशन को प्रबंधित करता है।
  • window.history: ब्राउज़र का हिस्ट्री डेटा एक्सेस करता है और आगे और पीछे नेविगेशन की अनुमति देता है।
  • window.navigator: ब्राउज़र और डिवाइस के बारे में जानकारी प्रदान करता है।
  • window.innerWidth / window.innerHeight: व्यूपोर्ट की चौड़ाई और ऊंचाई प्राप्त करता है।

मेथड्स

 1// Show an alert
 2window.alert('Hello, this is an alert!');
 3
 4// Show a confirmation dialog
 5if (window.confirm('Are you sure you want to proceed?')) {
 6    console.log('User clicked OK');
 7} else {
 8    console.log('User clicked Cancel');
 9}
10
11// Show a prompt dialog
12const userInput = window.prompt('Please enter your name:');
13console.log(`Hello, ${userInput}!`);
14
15// Open a new tab
16window.open('https://www.example.com', '_blank');
17
18// Display a message after 3 seconds
19window.setTimeout(() => {
20    console.log('This message appears after 3 seconds!');
21}, 3000);
22
23// Display a message every second
24const intervalId = window.setInterval(() => {
25    console.log('This message appears every second!');
26}, 1000);
27
28// Clear the interval after 5 seconds
29setTimeout(() => {
30    clearInterval(intervalId);
31    console.log('Interval cleared.');
32}, 5000);
  • window.alert(): एक एलर्ट डायलॉग प्रदर्शित करता है।
  • window.confirm(): एक डायलॉग प्रदर्शित करता है जो उपयोगकर्ता से पुष्टि मांगता है और OK या Cancel का परिणाम लौटाता है।
  • window.prompt(): उपयोगकर्ता से इनपुट के लिए एक डायलॉग प्रदर्शित करता है और दर्ज की गई मान को प्राप्त करता है।
  • window.open(): एक नई विंडो या टैब खोलता है।
  • window.setTimeout() / window.setInterval(): एक टाइमर सेट करता है जो किसी फ़ंक्शन को निर्दिष्ट समय या नियमित अंतराल पर निष्पादित करता है।

इवेंट हैंडलिंग

 1// Display a message when the page is fully loaded
 2window.onload = () => {
 3    console.log('Page is fully loaded!');
 4};
 5
 6// Display a message when the window is resized
 7window.onresize = () => {
 8    console.log('Window resized! New size:', window.innerWidth, 'x', window.innerHeight);
 9};
10
11// Display a message when the page is being scrolled
12window.onscroll = () => {
13    console.log('Page is being scrolled!');
14};
  • window.onload: यह इवेंट तब सक्रिय होता है जब पेज पूरी तरह लोड हो जाता है।
  • window.onresize: यह इवेंट तब सक्रिय होता है जब विंडो का आकार बदला जाता है।
  • window.onscroll: यह इवेंट तब सक्रिय होता है जब उपयोगकर्ता पेज को स्क्रॉल करता है।

वैश्विक चर के रूप में भूमिका

1var myVar = 10;
2console.log(window.myVar); // 10
  • window वस्तु वैश्विक चर और फ़ंक्शन को धारण करती है। अन्य शब्दों में, घोषित चर और फ़ंक्शन स्वतः ही window की प्रॉपर्टी बन जाते हैं।

जावास्क्रिप्ट में DOM में हेरफेर

जावास्क्रिप्ट DOM (डॉक्यूमेंट ऑब्जेक्ट मॉडल) में हेरफेर का उपयोग वेब पेज पर तत्वों के साथ डायनामिक रूप से इंटरैक्ट करने के लिए किया जाता है। DOM एक HTML दस्तावेज़ की संरचना को एक पेड़ के रूप में दर्शाता है, जिसे जावास्क्रिप्ट का उपयोग करके संरचना को संशोधित करने और पेज की डिस्प्ले को नियंत्रित करने के लिए बदला जा सकता है।

DOM की मूल बातें

DOM वेबपेज के HTML को ऑब्जेक्ट के रूप में मानता है, जिससे तत्वों और गुणों तक पहुंचने और संशोधित करने की अनुमति मिलती है। HTML दस्तावेज़ तक पहुंचने के लिए document वस्तु का उपयोग करें।

DOM तत्व प्राप्त करना

जावास्क्रिप्ट में DOM के तत्वों तक पहुंचने के लिए कई तरीके हैं।

  • document.getElementById(): id एट्रिब्यूट द्वारा एक एलिमेंट प्राप्त करता है।
  • document.getElementsByClassName(): क्लास नाम द्वारा एलिमेंट्स प्राप्त करता है। HTMLCollection लौटाता है। HTMLCollection एक जीवित संग्रह है जो DOM में बदलावों को वास्तविक समय में दर्शाता है।
  • document.getElementsByTagName(): टैग नाम द्वारा एलिमेंट्स प्राप्त करता है। HTMLCollection लौटाता है।
  • document.querySelector(): पहले मिलते हुए एलिमेंट को प्राप्त करने के लिए CSS सेलेक्टर का उपयोग करता है।
  • document.querySelectorAll(): सभी मिलते हुए एलिमेंट्स को प्राप्त करने के लिए CSS सेलेक्टर का उपयोग करता है। NodeList लौटाता है। NodeList एक स्थैतिक संग्रह है, जो प्राप्ति के समय की स्थिति को रखता है और DOM में बाद के बदलावों को नहीं दर्शाता है।

उदाहरण: getElementById और querySelector

1<div id="content">Hello, World!</div>
2<button id="changeText">Change Text</button>
1const content = document.getElementById('content');
2console.log(content.textContent); // "Hello, World!"
3
4const button = document.querySelector('#changeText');

DOM में हेरफेर

प्राप्त तत्वों पर विभिन्न ऑपरेशन किए जा सकते हैं।

पाठ बदलना

किसी तत्व के पाठ को बदलने के लिए textContent या innerHTML का उपयोग करें।

  • textContent: किसी तत्व की पाठ सामग्री प्राप्त करें या उसे बदलें। HTML टैग व्याख्या नहीं किए जाते।
  • innerHTML: किसी तत्व की HTML सामग्री प्राप्त करें या उसे बदलें। HTML टैग वाली स्ट्रिंग्स को भी प्रोसेस किया जाता है।
1content.textContent = 'Hello, world!';  // Change the text
2button.innerHTML = '<strong>Click to change</strong>';  // Change including HTML

गुणों को बदलना

setAttribute() और getAttribute() का उपयोग करके तत्व के गुणों को बदलें।

1button.setAttribute('disabled', 'true');  // Disable the button
2const id = content.getAttribute('id');  // Get the "content"
3console.log(id);

CSS बदलना

CSS शैलियों को बदलने के लिए style प्रॉपर्टी का उपयोग करें।

1content.style.color = 'red';  // Change the text color to red
2content.style.fontSize = '20px';  // Change the font size

कक्षाओं में हेरफेर करना

तत्व से कक्षाओं को जोड़ने या हटाने के लिए classList का उपयोग करें।

  • add(): एक क्लास जोड़ता है।
  • remove(): एक क्लास हटाता है।
  • toggle(): यह निर्भर करता है कि क्लास मौजूद है या नहीं, उसे जोड़ता या हटाता है।
  • contains(): यह जांचता है कि कोई क्लास मौजूद है या नहीं।
1content.classList.add('highlight');  // Add a class
2button.classList.toggle('active');   // Toggle a class

DOM तत्वों को बनाना और हटाना

नए तत्व बनाना

एक नया तत्व बनाने और उसे DOM में जोड़ने के लिए document.createElement() का उपयोग करें।

1const newDiv = document.createElement('div');  // Create a new div element
2newDiv.textContent = 'This is a new element';
3document.body.appendChild(newDiv);  // Append to the body element

तत्वों को हटाना

एक तत्व को हटाने के लिए remove() विधि का उपयोग करें।

1newDiv.remove();  // Remove the created element

घटनाएं जोड़ना

DOM हेरफेर के भाग के रूप में, आप उपयोगकर्ता क्रियाओं का जवाब देने वाले घटना हैंडलर जोड़ सकते हैं। क्लिक और कीबोर्ड इंटरैक्शन जैसी घटनाओं को संभालने के लिए addEventListener() का उपयोग करें।

1button.addEventListener('click', () => {
2    content.textContent = 'The text has been changed';
3});

इस उदाहरण में, बटन पर क्लिक करने से #content तत्व का पाठ बदल जाता है।

DOM वृक्ष में नेविगेट करना

आप माता-पिता और सहोदर तत्वों तक पहुंचने के लिए DOM में नेविगेट कर सकते हैं।

  • parentNode: पेरेंट नोड तक पहुँचता है।
  • childNodes: चाइल्ड नोड्स तक पहुँचता है। आप सभी प्रकार के नोड्स तक पहुँच सकते हैं, न केवल एलिमेंट नोड्स जैसे कि HTML टैग्स, बल्कि टेक्स्ट नोड्स और कमेंट नोड्स भी।
  • firstChild / lastChild: पहले और अंतिम चाइल्ड एलिमेंट्स तक पहुँचता है।
  • nextSibling / previousSibling: अगले और पिछले सिबलिंग एलिमेंट्स तक पहुँचता है।
1const parent = content.parentNode;  // Get the parent element
2const firstChild = parent.firstChild;  // Get the first child element
3console.log(firstChild);

उदाहरण: एक सूची में एक नया आइटम जोड़ना

यहां सूची में एक नया आइटम जोड़ने का एक उदाहरण दिया गया है।

 1// Get the container element where the HTML will be inserted
 2const content = document.getElementById('content');
 3
 4// Create the <ul> element with id="list"
 5const list = document.createElement('ul');
 6list.id = 'list';
 7
 8// Add initial list items
 9const item1 = document.createElement('li');
10item1.textContent = 'Item 1';
11list.appendChild(item1);
12
13const item2 = document.createElement('li');
14item2.textContent = 'Item 2';
15list.appendChild(item2);
16
17// Create the <button> element with id="addItem"
18const addItemButton = document.createElement('button');
19addItemButton.id = 'addItem';
20addItemButton.textContent = 'Add Item';
21
22// Append the list and button to the content container
23content.appendChild(list);
24content.appendChild(addItemButton);
25
26// Add event listener to the button
27addItemButton.addEventListener('click', () => {
28    const newItem = document.createElement('li');
29    newItem.textContent = 'New Item';
30    list.appendChild(newItem);
31});

इस कोड में, "आइटम जोड़ें" बटन पर क्लिक करने से सूची में एक नया <li> तत्व जुड़ जाता है।

सारांश

  • JavaScript DOM में हेरफेर आपको एक HTML दस्तावेज़ के भीतर तत्वों को प्राप्त करने, बदलने, बनाने और हटाने की अनुमति देता है।
  • आप getElementById() और querySelector() जैसे तरीकों का उपयोग करके तत्व प्राप्त कर सकते हैं।
  • पाठ और HTML बदलने के लिए textContent या innerHTML का उपयोग करें, और विशेषताओं को बदलने के लिए setAttribute() का उपयोग करें।
  • नए तत्व बनाने के लिए createElement() का उपयोग करें और उन्हें हटाने के लिए remove() का उपयोग करें।
  • आप ईवेंट हैंडलिंग के माध्यम से उपयोगकर्ता कार्यों का उत्तर देने वाले इंटरएक्टिव वेब पेज बना सकते हैं।

आप हमारे YouTube चैनल पर Visual Studio Code का उपयोग करके ऊपर दिए गए लेख के साथ आगे बढ़ सकते हैं। कृपया YouTube चैनल को भी देखें।

YouTube Video