How to change body css elements inside iframe?

by wilmer.lemke , in category: HTML & CSS , 2 months ago

How to change body css elements inside iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@wilmer.lemke 

To change the body CSS elements inside an iframe, you can use the following steps:

  1. Get access to the iframe element in your HTML document using JavaScript. You can achieve this using the contentWindow property of the iframe element.
1
2
const iframe = document.querySelector('iframe');
const iframeDocument = iframe.contentWindow.document;


  1. Once you have access to the iframe document, you can manipulate its body CSS elements using standard JavaScript or jQuery selectors and methods.


For example, you can change the background color of the body inside the iframe:

1
iframeDocument.querySelector('body').style.backgroundColor = 'red';


  1. You can also apply more complex CSS changes by adding classes or inline styles to the body element inside the iframe.
1
2
3
4
5
// Add a class to the body element
iframeDocument.querySelector('body').classList.add('new-class');

// Apply inline styles to the body element
iframeDocument.querySelector('body').style.fontSize = '24px';


  1. Ensure that the content inside the iframe is from the same origin as the parent document to avoid security restrictions. If the iframe content is from a different origin, you may encounter cross-origin security issues.


By following these steps, you can change body CSS elements inside an iframe using JavaScript.