How To Change HTML Object Element Data Attribute Value in Javascript - Stack Overflow
How To Change HTML Object Element Data Attribute Value in Javascript - Stack Overflow
Asked
12 years, 1 month ago Modified
5 years, 6 months ago Viewed
135k times
How do you change HTML Object element data attribute value in JavaScript?
element.setAttribute("data", "http://www.google.com");
Share Follow edited Jul 10, 2014 at 11:05 asked Jan 29, 2011 at 10:17
Sid M user587159
4,358 4 29 50 337 1 4 6
1 What have you tried? What didn't work? Can you post your HTML and javascript?
– Oded
Jan 29, 2011 at
10:23
Report this ad
Sorted by:
6 Answers
Highest score (default)
This works:
52
<html>
<head></head>
<body>
<script type="text/javascript">
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.
Share Follow edited Jan 29, 2011 at 11:31 answered Jan 29, 2011 at 10:24
Richard H
37.5k 37 110 138
I have tried with those but no fruit , can you please post sample example that you have tested thanks
– user587159
Jan 29, 2011 at 10:37
26 For example:
avatar.dataset.id = 12345;
Reference:
https://developer.mozilla.org/en/docs/Web/API/HTMLElement/dataset
Share Follow edited Nov 1, 2016 at 7:39 answered Nov 1, 2016 at 6:30
jacefarm Vignesh Manogar
6,549 6 36 46 479 5 6
1 Excellent ! Exactly what i was looking for.
– electo
Nov 5, 2020 at 14:02
document.getElementById("PdfContentArea").setAttribute('data', path);
6
OR
Share Follow edited Sep 4, 2017 at 2:17 answered Sep 4, 2017 at 2:13
Robert Moskal Patrick Wong
21.4k 8 61 85 61 1 2
and in jquery:
i.e
$('a').attr('href','http://www.stackoverflow.com/')
this works but when I want to change value again it doesn't work. for example : $ ('a') .attr ('data', 'http:
//www.stackoverflow.com/1.pdf') ok change again $ ('a') .attr ('href', 'http:
//www.stackoverflow.com/2.pdf') does not show. any suggestion. regards
– Alberto Lujan
May 31, 2021 at
23:18
The behavior of host objects <object> is due to ECMA262 implementation dependent and set
attribute by setAttribute() method may fail.
2
I see two solutions:
2. hard: remove object from DOM tree and create new one with changed data attribute.
Share Follow edited Jul 9, 2014 at 14:26 answered Jul 9, 2014 at 14:03
drs user3283655
5,489 4 41 67 31 1