Revised Response following changes to the question:
The usage of the identifier Object
is strongly discouraged. It is advisable to modify both the id
and the variable name you are using. For instance:
<div id="theObject" titleDiv="blank"></div>
and
var theObject=document.getElementById('theObject');
theObject.setAttribute("titleDiv","myDiv");
Avoid using reserved JavaScript functions such as Object
, Function
, Date
, etc., as values for the id
attribute due to their global namespace implications. This practice can lead to confusion among developers and should be avoided as variable names as well.
Although changing the id
and variable name is recommended, it may not necessarily solve the problem as noted below.
Initial Answer:
The setAttribute
method should be called on an actual DOM element instance, rather than using the built-in Object
function.
If you target a specific DOM element, the functionality works (even on IE9):
(function() {
// Obtain the corresponding DOM element
var target = document.getElementById("target");
// Set the attribute
target.setAttribute("titleDiv","myDiv");
// Displaying the result
display("Result: " + target.getAttribute("titleDiv"));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
Live Demo | source
Inspect the HTML tab using F12 developer tools to verify that the div
indeed has the attribute. Ensure to use dev tools instead of "view source," which displays the initial server-sent HTML, not the current DOM state.
A side note: Employing custom attributes without adhering to the data-
prefix is not recommended. You might want to communicate this concern to those overseeing these decisions. Nonetheless, this issue is unlikely the root cause of your current dilemma.