Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change HTML Object element data attribute value in javascript

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"); 
like image 690
user587159 Avatar asked Jan 29 '11 10:01

user587159


People also ask

How JavaScript can change HTML attribute values?

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.

How do you get the value of data attribute in JS?

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.

How do you value a data attribute?

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.

How set data attribute in HTML?

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.


2 Answers

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.

like image 179
Richard H Avatar answered Sep 17 '22 06:09

Richard H


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

like image 34
Vignesh Manogar Avatar answered Sep 17 '22 06:09

Vignesh Manogar