How do you change HTML Object element data attribute value in JavaScript?
Here is what i am trying
<object type="text/html" id="htmlFrame" style="border: none;" standby="loading" width="100%"></object> var element = document.getElementById("htmlFrame"); element.setAttribute("data", "http://www.google.com");
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.
Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
One way to get the value of an attribute is to use the getAttribute method available natively. We can call getAttribute to return the value of the data-fruit attribute by writing; const plant = document.
Creating an HTML Data Attribute Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
This works:
<html> <head></head> <body> <object type="text/html" id="htmlFrame" style="border: none;" standby="loading" width="100%"></object> <script type="text/javascript"> var element = document.getElementById("htmlFrame"); element.setAttribute("data", "attributeValue"); </script> </body> </html>
If you put this in a file, open in it a web browser, the javascript will execute and and the "data" attribute + value will be added to the object element.
Note: If you simply look at the HTML source, you wil NOT see the attribute. This is because the browser is showing you the static source sent by the webserver, NOT the dynamically rendered DOM. To inspect the DOM, use a tool like Firebug. This will show you what DOM the browser has rendered, and you will be able to see the added attribute.
Using Firefox + Firebug or Google Chrome, you can right click on a part of a page and do "Inspect Element". This will bring up a view of the rendered DOM.
In JavaScript, you can assign values to data attributes through Element.dataset.
For example:
avatar.dataset.id = 12345;
Reference: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/dataset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With