How to delete html elements in an iframe using javascript?

by arnoldo.moen , in category: Javascript , 14 days ago

How to delete html elements in an iframe using javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 13 days ago

@arnoldo.moen 

To delete HTML elements inside an iframe using JavaScript, you can use the contentDocument property of the iframe to access the document inside the iframe and then use standard DOM manipulation methods to delete the desired elements.


Here is an example code snippet that demonstrates how to delete an element with a specific id inside an iframe:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Get the iframe element
var iframe = document.getElementById('myIframe');

// Access the document inside the iframe
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

// Find the element with a specific id and delete it
var elementToDelete = iframeDocument.getElementById('elementToDelete');
if (elementToDelete) {
    elementToDelete.parentNode.removeChild(elementToDelete);
}


In this code snippet:

  1. Replace 'myIframe' with the id of your iframe element.
  2. Replace 'elementToDelete' with the id of the HTML element you want to delete inside the iframe.


Make sure that your iframe and the content inside the iframe are hosted on the same domain, as the same-origin policy restricts access to content in iframes from different domains.