dom-examples
Code examples that accompany various MDN DOM and Web API documentation pages
Top Related Projects
Quick Overview
The mdn/dom-examples repository is a collection of small, focused examples demonstrating various DOM (Document Object Model) APIs and related technologies. It serves as a companion to the MDN Web Docs, providing practical code samples for developers to learn from and experiment with.
Pros
- Comprehensive coverage of DOM APIs and related web technologies
- Well-organized structure with separate directories for different topics
- Regularly updated to reflect modern web development practices
- Directly linked to MDN documentation for easy reference
Cons
- Some examples may be too simplistic for advanced developers
- Not all examples are fully cross-browser compatible
- Limited explanations within the code itself; relies on accompanying MDN documentation
- Some older examples may not reflect the latest best practices
Code Examples
- Creating and appending elements:
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
- Adding event listeners:
const button = document.querySelector('#myButton');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
- Using Intersection Observer:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
});
const elements = document.querySelectorAll('.lazy-load');
elements.forEach(el => observer.observe(el));
Getting Started
To use these examples:
-
Clone the repository:
git clone https://github.com/mdn/dom-examples.git
-
Navigate to the desired example directory:
cd dom-examples/example-directory
-
Open the HTML file in a web browser to see the example in action.
-
Explore the JavaScript and CSS files to understand how the example works.
-
Refer to the linked MDN documentation for detailed explanations and additional context.
Competitor Comparisons
Test suites for Web platform specs — including WHATWG, W3C, and others
Pros of wpt
- Comprehensive test suite covering a wide range of web platform features
- Collaborative effort with contributions from major browser vendors
- Regularly updated to reflect the latest web standards and specifications
Cons of wpt
- More complex and harder to navigate for beginners
- Focuses on testing rather than providing simple, educational examples
- Requires more setup and understanding of the testing framework
Code Comparison
mdn/dom-examples:
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
web-platform-tests/wpt:
test(() => {
const button = document.createElement('button');
assert_true(button instanceof HTMLButtonElement);
assert_equals(button.type, 'submit');
}, 'HTMLButtonElement interface object');
The mdn/dom-examples repository provides simple, practical examples for learning DOM manipulation, while web-platform-tests/wpt focuses on comprehensive testing of web platform features. The code snippets illustrate this difference, with mdn/dom-examples showing a basic event listener setup, and wpt demonstrating a more complex test case for button element properties.
DOM Standard
Pros of dom
- Official specification repository, providing the most up-to-date and authoritative DOM standard
- Includes detailed explanations and rationales for DOM features and behaviors
- Allows direct contribution to the DOM standard through issues and pull requests
Cons of dom
- More complex and technical content, less beginner-friendly
- Focuses on specification rather than practical examples
- May lack context for real-world usage scenarios
Code comparison
dom-examples:
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
dom:
interface Element : Node {
[SameObject] readonly attribute DOMTokenList classList;
[CEReactions] attribute DOMString className;
[CEReactions] attribute DOMString id;
[CEReactions] attribute DOMString slot;
};
The dom-examples repository provides practical JavaScript code samples, while the dom repository focuses on Web IDL interface definitions for the DOM specification.
dom-examples is more suitable for developers learning DOM manipulation, offering hands-on examples. dom is better for those interested in the technical details of the DOM standard or contributing to its development.
Both repositories serve different purposes: dom-examples for practical learning and dom for specification and standardization. Developers may find value in using both, depending on their needs and expertise level.
A repo containing samples tied to new functionality in each release of Google Chrome.
Pros of samples
- More extensive collection of examples covering a wider range of Chrome and web APIs
- Regularly updated with new features and APIs as they become available in Chrome
- Includes examples for cutting-edge web technologies and experimental features
Cons of samples
- Focused primarily on Chrome-specific features, which may not work in other browsers
- Less beginner-friendly, with more complex examples and less detailed explanations
- May contain deprecated or experimental features that are subject to change
Code Comparison
samples (Service Worker example):
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
dom-examples (Service Worker example):
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => response || fetch(event.request))
);
});
Both examples demonstrate a basic service worker fetch event handler, but samples tends to use older function syntax, while dom-examples uses more modern arrow functions.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
dom-examples
Code examples that accompany various MDN DOM and Web API documentation pages.
[!NOTE] You can include an example directly in MDN pages using
{{EmbedLiveSample()}}
macros or regular Markdown code blocks. These methods are simpler to maintain as the code lives beside the rest of the content. Only add examples to this repository if your example doesn't easily run on MDN pages for technical or security reasons.
Repository contents
-
The "abort-api" directory contains an example of how to use the "Abort API" (aka AbortSignal and AbortController). Run the example live.
-
The "audiocontext-setsinkid" directory contains an example of how to use the
AudioContext.setSinkId()
method and related features. Run the example live. -
The "auxclick" directory contains a basic example demonstrating the new
auxclick
event type. See GlobalEventHandlers.auxclick for more details, or run the example live. -
The "canvas" directory contains an example "chroma-keying" demonstrating how to use the Canvas API to manipulate videos: see Manipulating video using canvas or run the example live.
-
The "channel-messaging-basic" directory contains a basic example demonstrating the basics of channel messaging; see Channel Messaging API or run the example live.
-
The "channel-messaging-multimessage" directory contains another channel messaging demo, showing how multiple messages can be sent between browsing contexts. See Channel Messaging API for more details. Run the demo live.
-
The "css-painting" directory contains examples demonstrating the CSS Painting API. See the examples live.
-
The "drag-and-drop" directory is for examples and demos of the HTML Drag and Drop standard.
-
The "document-picture-in-picture" directory contains an example showing usage of the Document Picture-in-Picture API. See the example live.
-
The "edit-context" directory contains examples demonstrating the EditContext API. See the list of examples.
-
The "fullscreen-api" directory is for examples and demos of the Fullscreen API. Run the example live.
-
The "history-api" directory contains an example that demonstrates the History API. View the demo live.
-
The "indexeddb-api" directory contains a demo for the IndexedDB API.
-
The "insert-adjacent" directory contains basic demos for insertAdjacentElement and insertAdjacentText.
-
The "matchmedia" directory contains a basic demo to test matchMedia functionality. See Window.matchMedia for more details. Run the demo live.
-
The "mediaquerylist" directory contains a basic demo to test more advanced matchMedia/mediaquerylist functionality. See MediaQueryList for more details. Run the demo live.
-
The "media" directory contains examples and demos showing how to use HTML and DOM media elements and APIs.
-
The "payment-request" directory contains examples of the Payment Request API.
-
The "pointerevents" directory is for examples and demos of the Pointer Events standard.
-
The "pointer-lock" directory contains a basic demo to show usage of the Pointer Lock API. You can find more explanation of how the demo works at the main MDN Pointer Lock API page. Run the demo live.
-
The "popover-api" directory is for examples and demos of the Popover API standard. Go to the Popover API demo index to see what's available.
-
The "reporting-api" directory contains a couple of basic demos to show usage of the Reporting API. You can find more explanation of how the API works in the main MDN Reporting API docs. Run the deprecation report demo live.
-
The "resize-event" directory contains a basic demo to show how you can use the resize event. Resize the browser window either by height or width to see the size of your current window. Run the demo live.
-
The "screenleft-screentop" directory contains a demo to show how you could use the Window.screenLeft and Window.screenTop properties to draw a circle on a canvas that always stays in the same physical place on the screen when you move your browser window. Run the demo live.
-
The "scrolltooptions" directory contains a demo to show how you could use the ScrollToOptions dictionary along with the Window.ScrollTo() method to programmatically scroll a web page. Run the demo live.
-
The "server-sent-events" directory contains a very basic SSE demo that uses PHP to create the server. You can find more information in our Using server-sent events article. To run the demo you'll need to serve the files from a server that supports PHP; MAMP is a good PHP test server environment.
-
The "service-worker/simple-service-worker" directory contains a simple demo showing how to use the
Service Worker API
to manage your page's cache. Run the demo live. -
The "sourcebuffer" directory contains a basic demo to show usage of the
SourceBuffer
interface. Run the demo live. -
The "streams" directory contains demos of the Streams API for using low-level I/O processing.
-
The "touchevents" directory is for examples and demos of the Touch Events standard.
-
The "visual-viewport-api" directory contains a basic demo to show usage of the Visual Viewport API. For more details on how it works, read Visual Viewport API. View the demo live.
-
The "web-animations-api" directory contains Web Animation API demos. See the web animations README for more information.
-
The "web-storage" directory contains a basic demo to show usage of the Web Storage API. For more detail on how it works, read Using the Web Storage API. View the demo live.
-
The "view-transitions" directory contains demos to show usage of the View Transitions API, both for single-page app View the SPA demo live and multiple-page app View the MPA demo live view transitions.
-
The "web-share" directory contains a basic demo to show usage of the Web Share API. View the demo live.
-
The "web-workers" directory contains a basic web worker to demonstrate how Web Workers work. View the demo live.
-
The "webgl-examples" directory contains a number of WebGL examples that demonstrate the WebGL API, which is used for 2D and 3D graphics on the web.
-
The "webgpu-compute-demo" directory contains an example that demonstrates basic usage of the WebGPU API compute pipeline, which is used for performing general computation on the GPU. View the demo live.
-
The "webgpu-render-demo" directory contains an example that demonstrates basic usage of the WebGPU API render pipeline, which is used for rendering high-performance graphics via the GPU. View the demo live.
-
The "window-management-api" directory contains a basic demo to show usage of the Window Management API. View the demo live.
Contribute to MDN Web Docs
You can contribute to MDN Web Docs and be a part of our community through content contributions, engineering, or translation work. The MDN Web Docs project welcomes contributions from everyone who shares our goals and wants to contribute constructively and respectfully within our community.
To find out how to get started, see the CONTRIBUTING.md document in this repository. By participating in and contributing to our projects and discussions, you acknowledge that you have read and agree to our Code of Conduct.
Get in touch
You can communicate with the MDN Web Docs team and community using the communication channels.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot