HTML Document embeds
Collection: A Deep Dive into Accessing Embed Elements
The document.embeds
collection in JavaScript provides a powerful way to access and manipulate all <embed>
elements within an HTML document. This collection is a live HTMLCollection
, which means that it automatically updates whenever <embed>
elements are added or removed from the document. This article will explore how to effectively use the document.embeds
collection, including its properties, methods, and practical examples.
What is the document.embeds
Collection?
The document.embeds
collection is a read-only property of the document
object in JavaScript. It returns an HTMLCollection
that contains all the <embed>
elements present in the document, in the order that they appear in the HTML.
The main purpose of document.embeds
is to enable developers to dynamically:
- Access embed elements to get information about them.
- Modify properties of embed elements.
- Perform actions based on the presence or state of embedded content.
Syntax
The syntax for accessing the document.embeds
collection is straightforward:
const embedsCollection = document.embeds;
Here, embedsCollection
is an HTMLCollection
containing all the <embed>
elements in the document.
Properties of the document.embeds
Collection
As an HTMLCollection
, document.embeds
has a few essential properties:
Property | Type | Description |
---|---|---|
`length` | Number | Returns the number of “ elements in the collection. |
Accessing Embed Elements
You can access individual <embed>
elements within the HTMLCollection
using their index or by iterating through the collection.
Accessing by Index
const firstEmbed = document.embeds[0]; // Access the first embed element
const secondEmbed = document.embeds[1]; // Access the second embed element, if it exists
Accessing by Iteration
You can use a for
loop, for...of
loop, or the forEach
method to iterate through the embeds
collection:
// Using a for loop
for (let i = 0; i < document.embeds.length; i++) {
const embedElement = document.embeds[i];
// Do something with embedElement
}
// Using a for...of loop
for (const embedElement of document.embeds) {
// Do something with embedElement
}
// Using forEach
document.embeds.forEach(embedElement => {
// Do something with embedElement
})
Examples
Let’s dive into some practical examples demonstrating how to use the document.embeds
collection. Each example includes HTML and JavaScript code to demonstrate a specific use case.
Example 1: Counting Embed Elements
This example demonstrates how to count the number of <embed>
elements in a document and display the count on the page.
<p>Number of Embed Elements: <span id="embedCount1"></span></p>
<embed
src="https://example.com/file.pdf"
type="application/pdf"
width="300"
height="200"
/>
<embed
src="https://example.com/video.mp4"
type="video/mp4"
width="320"
height="240"
/>
<script>
const embedCountDisplay1 = document.getElementById("embedCount1");
const numberOfEmbeds1 = document.embeds.length;
embedCountDisplay1.textContent = numberOfEmbeds1;
</script>
This code will display “Number of Embed Elements: 2” on the page, assuming that the HTML contains two embed tags.
Example 2: Displaying Embed Element Details
This example iterates through the document.embeds
collection and displays the src
attribute of each <embed>
element.
<ul id="embedDetails1"></ul>
<embed
src="https://example.com/audio.mp3"
type="audio/mpeg"
width="200"
height="20"
/>
<embed
src="https://example.com/flash.swf"
type="application/x-shockwave-flash"
width="400"
height="300"
/>
<script>
const embedDetailsList1 = document.getElementById("embedDetails1");
document.embeds.forEach((embed) => {
const listItem = document.createElement("li");
listItem.textContent = `Embed Source: ${embed.src}`;
embedDetailsList1.appendChild(listItem);
});
</script>
This code will display a list showing the src
of each embedded object:
- Embed Source: https://example.com/audio.mp3
- Embed Source: https://example.com/flash.swf
Example 3: Modifying Embed Element Attributes
This example demonstrates how to modify the width
and height
attributes of all <embed>
elements in the document using for
loop.
<embed
id="embedModify1"
src="https://example.com/document.pdf"
type="application/pdf"
width="300"
height="200"
/>
<embed
id="embedModify2"
src="https://example.com/other.pdf"
type="application/pdf"
width="300"
height="200"
/>
<script>
const allEmbeds = document.embeds
for(let i =0; i< allEmbeds.length; i++){
allEmbeds[i].width = "200";
allEmbeds[i].height = "150";
}
</script>
After running this script, the width of both embed elements will be set to “200”, and the height will be “150”.
Example 4: Conditional Actions Based on Embed Types
This example shows how to perform actions based on the type
of each <embed>
element.
<p id="embedStatus1"></p>
<embed
src="https://example.com/interactive.svg"
type="image/svg+xml"
width="250"
height="250"
/>
<embed
src="https://example.com/presentation.ppt"
type="application/vnd.ms-powerpoint"
width="350"
height="350"
/>
<script>
const embedStatusDisplay1 = document.getElementById("embedStatus1");
let message = "";
document.embeds.forEach((embed) => {
if (embed.type === "image/svg+xml") {
message += "SVG embed found. ";
} else if (embed.type === "application/vnd.ms-powerpoint") {
message += "PowerPoint embed found. ";
}
});
embedStatusDisplay1.textContent = message;
</script>
This code will display the message “SVG embed found. PowerPoint embed found.” on the page.
Example 5: Dynamic Embed Modification
This example demonstrates how the document.embeds
live collection automatically updates when an embed element is added dynamically.
<ul id="embedList2"></ul>
<button id="addEmbedButton">Add Embed</button>
<script>
const embedList2 = document.getElementById("embedList2");
const addEmbedButton = document.getElementById("addEmbedButton");
function updateEmbedList() {
embedList2.innerHTML = "";
for (const embed of document.embeds) {
const listItem = document.createElement("li");
listItem.textContent = `Embed Source: ${embed.src}`;
embedList2.appendChild(listItem);
}
}
addEmbedButton.addEventListener("click", function () {
const newEmbed = document.createElement("embed");
newEmbed.src = "https://example.com/newembed.pdf";
newEmbed.type = "application/pdf";
newEmbed.width = "200";
newEmbed.height = "150";
document.body.appendChild(newEmbed);
updateEmbedList();
});
updateEmbedList();
</script>
Initially, the list will be empty. Each time you click the button, a new embed element is added, and the list is updated to reflect the changes.
Tips and Best Practices
- Check for
embeds
Collection: Before usingdocument.embeds
, ensure that your script is running in a browser environment and not a non-browser environment. - Live Collection: Be aware that
document.embeds
is a live collection. Any changes to the HTML document (adding or removing elements) will be immediately reflected in the collection. - Avoid Direct Modification: While you can modify attributes of individual elements using the collection, you cannot directly add, or remove elements from the collection. Use DOM methods like
appendChild()
andremove()
for this purpose. - Performance: While iterating through the collection, make sure to only perform necessary operations to improve performance. Avoid complex calculations or rendering operations during iteration.
- Error Handling: Always check if
document.embeds
exists and is notnull
to prevent potential script errors.
Browser Compatibility
The document.embeds
collection is supported by all major modern web browsers:
- Chrome
- Firefox
- Safari
- Edge
- Opera
Conclusion
The document.embeds
collection is a valuable tool for web developers looking to access and manipulate embed elements within an HTML document. Understanding how to use this collection effectively allows for the creation of more dynamic and interactive web applications, giving you fine-grained control over embedded content. By following the examples and best practices in this guide, you can leverage the document.embeds
collection to enhance your web development projects.