JavaScript at HTML

JavaScript at HTML

Ipinaliwanag ng artikulong ito ang JavaScript at 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>

Ang Obhektong window sa JavaScript

Ang obhektong window sa JavaScript ay ang global na obhekt sa isang kapaligiran ng browser, na nagbibigay ng mga function at impormasyon na may kaugnayan sa web page at bintana ng browser. Dahil ang window ay ang global na saklaw ng browser, ang lahat ng JavaScript code na tumatakbo sa browser ay nagiging bahagi ng obhektong window. Ang obhektong window ay may mahalagang papel sa pagpapatakbo ng JavaScript sa kapaligiran ng browser, na nagbibigay ng maraming API at mga katangian.

Pangunahing Mga Tampok ng Obhektong window

Mga Katangian

 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: Ina-access ang kasalukuyang HTML na dokumento.
  • window.location: Pinamamahalaan ang kasalukuyang URL at pag-navigate ng browser.
  • window.history: Ina-access ang impormasyon ng history ng browser at nagbibigay-daan sa pasulong at pabalik na pag-navigate.
  • window.navigator: Nagbibigay ng impormasyon tungkol sa browser at device.
  • window.innerWidth / window.innerHeight: Kinukuha ang lapad at taas ng viewport.

Mga Pamamaraan

 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(): Nagpapakita ng dialog ng alerto.
  • window.confirm(): Nagpapakita ng dialog na humihingi ng kumpirmasyon mula sa user at nagbabalik ng resulta na OK o Kanselahin.
  • window.prompt(): Nagpapakita ng dialog para humingi ng user input at kinukuha ang ipinasok na halaga.
  • window.open(): Nagbubukas ng bagong bintana o tab.
  • window.setTimeout() / window.setInterval(): Nagse-set ng timer upang magpatupad ng function pagkatapos ng tiyak na oras o sa regular na pagitan.

Pangangalaga sa Mga Kaganapan

 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: Ang kaganapang ito ay napapatrigger kapag lubusang naiload ang pahina.
  • window.onresize: Ang kaganapang ito ay napapatrigger kapag ang window ay naiba ang laki.
  • window.onscroll: Ang kaganapang ito ay nagaganap kapag nag-scroll ang user sa pahina.

Papel bilang isang Global Variable

1var myVar = 10;
2console.log(window.myVar); // 10
  • Ang window object ay naglalaman ng mga global na variable at function. Sa madaling salita, ang mga idineklarang variable at function ay awtomatikong nagiging mga property ng window.

Pagmanipula ng DOM sa JavaScript

Ang pagmanipula ng JavaScript DOM (Document Object Model) ay ginagamit upang makipag-ugnayan nang dynamic sa mga elemento sa web page. Ipinapakita ng DOM ang istruktura ng isang HTML document bilang isang puno, na maaaring baguhin gamit ang JavaScript upang i-modify ang istruktura at kontrolin ang display ng pahina.

Mga Pangunahing Kaalaman ng DOM

Tinuturing ng DOM ang HTML ng isang webpage bilang mga object, na nagpapahintulot sa pag-access at pagbabago ng mga elemento at attribute. Gamitin ang document object upang ma-access ang HTML document.

Pagkuha ng mga Elemento ng DOM

May ilang mga paraan ang JavaScript upang ma-access ang mga elemento sa DOM.

  • document.getElementById(): Kumukuha ng elemento batay sa kanyang id attribute.
  • document.getElementsByClassName(): Kumukuha ng mga elemento batay sa pangalan ng klase. Nagbabalik ng HTMLCollection. Ang HTMLCollection ay isang buhay na koleksyon na nagpapakita ng pagbabago sa DOM sa totoong oras.
  • document.getElementsByTagName(): Kumukuha ng mga elemento batay sa pangalan ng tag. Nagbabalik ng HTMLCollection.
  • document.querySelector(): Gumagamit ng CSS selector upang kunin ang unang tugmang elemento.
  • document.querySelectorAll(): Gumagamit ng CSS selector upang kunin ang lahat ng tumutugmang elemento. Nagbabalik ng NodeList. Ang NodeList ay isang static na koleksyon na ipinapakita lamang ang kalagayan sa oras ng pagkuha at hindi nagpapakita ng mga kasunod na pagbabago sa DOM.

Halimbawa: getElementById at 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');

Pagmanipula ng DOM

Iba't ibang operasyon ang maaaring gawin sa mga elementong nakuha.

Pagbabago ng Teksto

Upang baguhin ang teksto ng isang elemento, gamitin ang textContent o innerHTML.

  • textContent: Kunin o baguhin ang nilalamang teksto ng isang elemento. Ang mga HTML tag ay hindi inuugnay.
  • innerHTML: Kunin o baguhin ang nilalamang HTML ng isang elemento. Ang mga string na naglalaman ng HTML tag ay ipinoproseso din.
1content.textContent = 'Hello, world!';  // Change the text
2button.innerHTML = '<strong>Click to change</strong>';  // Change including HTML

Pagbabago ng Mga Katangian

Gamitin ang setAttribute() at getAttribute() upang baguhin ang mga katangian ng elemento.

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

Pagbabago ng CSS

Gamitin ang ari-ariang style upang baguhin ang mga estilo ng CSS.

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

Pagmanipula ng Mga Klase

Gamitin ang classList upang magdagdag o magtanggal ng mga klase mula sa isang elemento.

  • add(): Nagdaragdag ng klase.
  • remove(): Nag-aalis ng klase.
  • toggle(): Nagdadagdag o nag-aalis ng klase depende kung ito ay umiiral.
  • contains(): Tinitingnan kung umiiral ang isang klase.
1content.classList.add('highlight');  // Add a class
2button.classList.toggle('active');   // Toggle a class

Paglikha at Pagbura ng mga Elemento ng DOM

Paglikha ng mga Bagong Elemento

Gamitin ang document.createElement() upang lumikha ng bagong elemento at idagdag ito sa DOM.

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

Pag-aalis ng Mga Elemento

Gamitin ang paraan ng remove() upang burahin ang isang elemento.

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

Pagdagdag ng Mga Kaganapan

Bilang bahagi ng manipulasyon ng DOM, maaari kang magdagdag ng mga tagapamahala ng kaganapan na tumutugon sa mga interaksyon ng gumagamit. Gamitin ang addEventListener() upang hawakan ang mga kaganapan tulad ng pag-click at mga interaksyon sa keyboard.

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

Sa halimbawang ito, ang pag-click sa isang pindutan ay binabago ang teksto ng elemento ng #content.

Pag-navigate sa Puno ng DOM

Maaari mong i-navigate ang DOM upang ma-access ang mga parent at sibling na elemento.

  • parentNode: Ikinukuha ang parent node.
  • childNodes: Ikinukuha ang mga anak na node. Maaari mong ma-access ang lahat ng uri ng mga node, hindi lang mga element node tulad ng HTML tag, kundi pati na rin ang mga text node at comment node.
  • firstChild / lastChild: Ikinukuha ang unang anak at huling anak na mga elemento.
  • nextSibling / previousSibling: Ikinukuha ang sumunod at naunang kapatid na mga elemento.
1const parent = content.parentNode;  // Get the parent element
2const firstChild = parent.firstChild;  // Get the first child element
3console.log(firstChild);

Halimbawa: Pagdaragdag ng Bagong Item sa Isang Listahan

Narito ang isang halimbawa ng pagdaragdag ng bagong item sa isang listahan.

 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});

Sa code na ito, ang pag-click sa button na "Add Item" ay nagdaragdag ng bagong <li> na elemento sa listahan.

Buod

  • Ang JavaScript DOM manipulation ay nagbibigay-daan sa iyo na makuha, baguhin, lumikha, at magtanggal ng mga elemento sa loob ng isang HTML na dokumento.
  • Maaari mong makuha ang mga elemento gamit ang mga pamamaraan tulad ng getElementById() at querySelector().
  • Gamitin ang textContent o innerHTML upang baguhin ang teksto at HTML, at ang setAttribute() upang manipulahin ang mga katangian.
  • Gamitin ang createElement() upang lumikha ng bagong mga elemento at ang remove() upang tanggalin ang mga ito.
  • Maaari kang lumikha ng mga interactive na mga web page na tumutugon sa mga aksyon ng user sa pamamagitan ng event handling.

Maaari mong sundan ang artikulo sa itaas gamit ang Visual Studio Code sa aming YouTube channel. Paki-check din ang aming YouTube channel.

YouTube Video