How to create html5 data attribute in an iframe?

by aniya.jaskolski , in category: HTML & CSS , 5 months ago

How to create html5 data attribute in an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@aniya.jaskolski 

To create an HTML5 data attribute in an iframe, you can use the setAttribute method to add the data attribute to the iframe element. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
    <title>Data Attribute in Iframe</title>
</head>
<body>
    <iframe id="myIframe" src="https://www.example.com"></iframe>
    
    <script>
        var iframe = document.getElementById("myIframe");
        iframe.setAttribute("data-example", "This is an example data attribute");
    </script>
</body>
</html>


In this example, we have an iframe element with the ID "myIframe". We use the getElementById method to get a reference to the iframe element and then use the setAttribute method to add a data attribute called "data-example" with the value "This is an example data attribute".


You can access this data attribute within the iframe using JavaScript by accessing the contentWindow property of the iframe and then using the getAttribute method on it.

1
2
3
var iframe = document.getElementById("myIframe");
var dataAttribute = iframe.contentWindow.document.body.getAttribute("data-example");
console.log(dataAttribute);


This code snippet will log the value of the data attribute "data-example" in the console.

Related Threads:

How to set src attribute of an iframe?
How to add an `iframe` as a background in html5?
How to set iframe src attribute?
How use <iframe> allow attribute?
How to create a border around iframe?
How to print an iframe with base64 data?