HTML DOM Embed Object: Accessing and Manipulating Embed Elements

The HTML DOM Embed object provides a way to interact with <embed> elements in your HTML document using JavaScript. The <embed> element is used to embed external resources, such as plugins or other content, into your web page. Through the DOM Embed object, you can access, modify, and control various attributes and properties of these embedded resources, enabling dynamic interactions and enhanced functionality.

Understanding the <embed> Element

The <embed> element is a versatile HTML element that allows you to integrate external content into your web page. Common uses for the <embed> element include:

  • Embedding media players (e.g., for audio and video).
  • Displaying PDF documents directly in the browser.
  • Integrating plugins or other interactive content.

The <embed> tag can have multiple attributes to define its behavior and source of the embedded content.

Purpose of the DOM Embed Object

The DOM Embed object is a critical interface that allows JavaScript to interact with the properties and behavior of the <embed> elements. You can use JavaScript to:

  • Access attributes: Get the src, type, width, height, and other attributes of the <embed> element.
  • Modify attributes: Change the attributes to dynamically update the embedded content.
  • Control behavior: Adjust settings like playback, volume, and other plugin-specific controls (if supported by the plugin).
  • Listen for events: Respond to events like load, error, or other embed-specific events.

Accessing Embed Elements

To begin working with <embed> elements, you first need to select the element using JavaScript. The common way is to use document.getElementById(), document.getElementsByTagName() or document.querySelector().

<embed id="myEmbed" src="sample.pdf" type="application/pdf" width="600" height="400">
const embedElement = document.getElementById("myEmbed");
console.log(embedElement); // Output: Embed Object

Here, embedElement is a variable that references the DOM Embed object.

Key Properties and Methods of the Embed Object

The Embed object provides access to various properties and methods that you can use to interact with the <embed> element. The most useful properties of Embed object are shown in the table below.

Property Type Description
`src` String Gets or sets the URL of the embedded resource.
`type` String Gets or sets the MIME type of the embedded resource.
`width` String Gets or sets the width of the embedded element, use `offsetWidth` to get the width in pixels.
`height` String Gets or sets the height of the embedded element, use `offsetHeight` to get the height in pixels.
`name` String Gets or sets the name of the embedded element.
`align` String Gets or sets how the element is aligned with its surrounding content.
`offsetWidth` Number Returns the layout width of the element, including border and padding, as an integer.
`offsetHeight` Number Returns the layout height of the element, including border and padding, as an integer.
`attributes` Object Returns a collection of all attribute nodes registered to the element.
`parentElement` Object Returns the parent element of the embed element.
`style` Object Returns the CSS style object for the element, allowing inline styles to be manipulated.

Note: The width and height attributes return strings of the values set in the HTML. To get the actual width and height in pixels, you should use offsetWidth and offsetHeight. 💡

Examples

Let’s explore several practical examples that demonstrate how to use the DOM Embed object.

Basic Attribute Access and Modification

In this example, we’ll access basic attributes of the <embed> element and then change its src dynamically.

<embed
  id="embedBasic"
  src="sample.pdf"
  type="application/pdf"
  width="400"
  height="300"
/>
<button onclick="changeEmbed()">Change Embed Source</button>

<script>


  const embedBasicElement = document.getElementById("embedBasic");
  console.log("Initial Source:", embedBasicElement.src);
  console.log("Embed Type:", embedBasicElement.type);
  console.log("Embed Width:", embedBasicElement.width);
  console.log("Embed Height:", embedBasicElement.height);

  function changeEmbed() {
    embedBasicElement.src = "another_sample.pdf";
  }


</script>

Output:

Initial Source: sample.pdf
Embed Type: application/pdf
Embed Width: 400
Embed Height: 300

After clicking the button, the embed src is changed to another_sample.pdf.

Getting Dimensions and Parent

This example demonstrates how to retrieve the actual width and height using offsetWidth and offsetHeight, and how to access the parent element.

<div id="embedContainer" style="border:1px solid black;">
<embed
  id="embedDimensions"
  src="sample.pdf"
  type="application/pdf"
  width="200"
  height="150"
  style="padding: 20px"
/>
</div>

<script>


    const embedDimensionsElement = document.getElementById("embedDimensions");
    const parentElement = embedDimensionsElement.parentElement;
    console.log("Embed Offset Width:", embedDimensionsElement.offsetWidth);
    console.log("Embed Offset Height:", embedDimensionsElement.offsetHeight);
    console.log("Parent Element:", parentElement);


</script>

Output:

Embed Offset Width: 240 // 200 width + 2*20 padding
Embed Offset Height: 190 // 150 height + 2*20 padding
Parent Element: <div id="embedContainer" style="border:1px solid black;"> ... </div>

Modifying Style and Attributes

This example shows how to use the style property to change the inline styles and update another attribute.

<embed id="embedStyle" src="sample.pdf" type="application/pdf" width="300" height="200" >
<button onclick="modifyStyle()">Modify Embed</button>

<script>


  const embedStyleElement = document.getElementById("embedStyle");

  function modifyStyle() {
    embedStyleElement.style.border = "2px solid red";
    embedStyleElement.style.boxShadow = "5px 5px 10px rgba(0,0,0,0.3)";
    embedStyleElement.width = "500";
  }


</script>

Clicking the button applies a red border, a box shadow, and expands the width of the embed element.

Accessing Attributes Collection

This example demonstrates how to retrieve and iterate through all attributes of the embed element using the attributes property.

<embed id="embedAttributes" src="sample.pdf" type="application/pdf" width="300" height="200" data-custom="my-data">

<script>


 const embedAttributesElement = document.getElementById('embedAttributes');
 const attributes = embedAttributesElement.attributes;
 console.log("List of attributes for the embed tag")
 for(let attribute of attributes){
    console.log(`${attribute.name}: ${attribute.value}`);
 }


</script>

Output:

List of attributes for the embed tag
src: sample.pdf
type: application/pdf
width: 300
height: 200
data-custom: my-data

Error Handling

Here is how you could listen for embed errors using an event listener.

<embed id="embedError" src="invalid.pdf" type="application/pdf" width="300" height="200">

<script>


 const embedErrorElement = document.getElementById("embedError");
 embedErrorElement.addEventListener("error", function(event) {
    console.error("Error loading embed:", event);
    alert("Error loading the embedded content.");
 });


</script>

If invalid.pdf does not exist, an error will be logged in console and an alert would be generated.

Real-World Applications

The HTML DOM Embed object finds use in scenarios such as:

  • Dynamic media players: Building interactive audio and video players with custom controls.
  • Document viewers: Creating web-based PDF viewers with zoom and navigation controls.
  • Interactive dashboards: Embedding and dynamically updating charts or visualizations.
  • Plugin integrations: Handling interactions with plugin-based content seamlessly.

Browser Support

The HTML DOM Embed object enjoys broad support across modern web browsers. It has good compatibility across the different browsers.

Note: While the Embed object is widely supported, the behavior and compatibility of embedded plugins can vary depending on the browser and the specific plugin used. Always test your implementations on different browsers to ensure consistent behavior. ⚠️

Conclusion

The HTML DOM Embed object provides essential tools for managing embedded content within web pages. Using this guide, you are now equipped to access, manipulate, and control the behavior of your <embed> elements, creating rich, dynamic, and engaging web applications. Understanding the properties and methods associated with the Embed object opens doors to powerful interactive features.