How to remove an element by class in an iframe?

Member

by mac , in category: Javascript , 4 months ago

How to remove an element by class in an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 4 months ago

@mac 

To remove an element by class in an iframe, you can use JavaScript to access the content of the iframe and manipulate its elements. Here is an example code snippet that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
  <title>Remove Element by Class in Iframe</title>
</head>
<body>

<iframe id="myIframe" src="https://www.example.com"></iframe>

<button onclick="removeElementByClass()">Remove Element</button>

<script>
function removeElementByClass() {
  var iframe = document.getElementById('myIframe');
  var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
  
  var element = iframeDoc.querySelector('.element-class'); // Replace 'element-class' with the class name of the element you want to remove
  
  if (element) {
    element.parentNode.removeChild(element);
  } else {
    console.log('Element not found');
  }
}
</script>

</body>
</html>


In this code snippet, we first define an iframe element with the id "myIframe" and a button that triggers the removeElementByClass function when clicked. Inside the function, we access the content of the iframe using iframe.contentDocument or iframe.contentWindow.document.


We then use iframeDoc.querySelector('.element-class') to select the element inside the iframe that has the specified class name (replace 'element-class' with the actual class name of the element you want to remove). If the element is found, we use element.parentNode.removeChild(element) to remove it from the DOM.


Note that this code assumes that the iframe source URL is from the same origin. If the iframe source URL is from a different origin, you may run into cross-origin security restrictions.