js_dom_examples
Modern JavaScript HTML DOM Examples
Section titled “Modern JavaScript HTML DOM Examples”Explore how to use modern JavaScript to dynamically access and manipulate HTML elements (DOM objects).
The Document Object
Section titled “The Document Object”The document object represents your web page. Here are common tasks:
- Get the document’s title:
const pageTitle = document.title; console.log(pageTitle); - Change the document’s title:
document.title = 'New Page Title'; - Get the document’s URL:
const pageURL = document.URL; console.log(pageURL); - Get the last modified date:
const lastModified = document.lastModified; console.log(lastModified); - Get the referring URL:
const referrer = document.referrer; console.log(referrer || 'No referrer'); - Read cookies:
const cookies = document.cookie; console.log(cookies);(Note: For robust cookie management, consider dedicated libraries or modern APIs like the Cookie Store API, thoughdocument.cookieis the basic access point). - Open a new window and write content:
const newWindow = window.open(); if (newWindow) { newWindow.document.write('<h1>Hello from new window!</h1>'); newWindow.document.close(); } else { console.error('Popup blocked!'); } - Get elements by tag name (returns a live HTMLCollection):
const paragraphs = document.getElementsByTagName('p'); console.log(Number of paragraphs: ${paragraphs.length}); - Get elements by name attribute (returns a live NodeList):
const emailFields = document.getElementsByName('email'); console.log(Number of email fields: ${emailFields.length}); - Select the first element matching a CSS selector:
const mainHeader = document.querySelector('#main-title'); if (mainHeader) mainHeader.textContent = 'Updated Title'; - Select all elements matching a CSS selector (returns a static NodeList):
const listItems = document.querySelectorAll('.item'); listItems.forEach(item => console.log(item.textContent));
Understanding the Document Object: The document object is the entry point to the content of a page. Modern methods like querySelector and querySelectorAll provide powerful and flexible ways to select elements using CSS selectors. Learn more on MDN Web Docs: Document
Working with Specific Element Collections
Section titled “Working with Specific Element Collections”While modern querySelectorAll is often preferred for its versatility, JavaScript still provides access to specific live HTMLCollections:
Anchors Collection (document.anchors)
Section titled “Anchors Collection (document.anchors)”Find the number of anchors: const numAnchors = document.anchors.length; console.log(Number of anchors: ${numAnchors});
Find the text content of the first anchor: if (document.anchors.length > 0) { console.log(document.anchors[0].textContent); }
Modern alternative: const allLinks = document.querySelectorAll('a[href]');
Links Collection (document.links)
Section titled “Links Collection (document.links)”Display the number of links: const numLinks = document.links.length; console.log(Number of links: ${numLinks});
Display the href attribute of the first link: if (document.links.length > 0) { console.log(document.links[0].href); }
Forms Collection (document.forms)
Section titled “Forms Collection (document.forms)”Find the number of forms: const numForms = document.forms.length; console.log(Number of forms: ${numForms});
Find the name or ID of the first form: if (document.forms.length > 0) { console.log(document.forms[0].name || document.forms[0].id); }
Images Collection (document.images)
Section titled “Images Collection (document.images)”Return the number of images: const numImages = document.images.length; console.log(Number of images: ${numImages});
Return the id of the first image: if (document.images.length > 0) { console.log(document.images[0].id); }
CSS Manipulation with JavaScript
Section titled “CSS Manipulation with JavaScript”Change the visibility of an HTML element:
const elementToToggle = document.getElementById('myElement'); if (elementToToggle) { elementToToggle.style.display = 'none'; /* To hide */ }
// To show it again: elementToToggle.style.display = 'block'; (or 'inline', 'flex', etc., depending on original display type)
Alternatively, use the hidden attribute: elementToToggle.hidden = true; or elementToToggle.hidden = false;
Change the background color of an HTML element:
const elementToColor = document.getElementById('myElement'); if (elementToColor) { elementToColor.style.backgroundColor = 'lightblue'; }
Best Practice: For more complex styling, it’s generally better to define CSS classes and use JavaScript to add or remove those classes:
// CSS: .is-hidden { display: none; } .highlight { background-color: yellow; }
// JS: element.classList.add('highlight'); element.classList.remove('is-hidden'); element.classList.toggle('another-class');