user1079065
user1079065

Reputation: 2205

IE 9 getAttribute method working

I am setting a custom attribute named (say) titleDiv by using setAttribute method

HTML code : <div id="Object" titleDiv="blank"></div>

Javascript code :

var Object=document.getElementById('Object'); Object.setAttribute("titleDiv","myDiv");

Which works fine in all the browser other than IE 9. Same thing happens for getAttribute also.

I have extensive use custom attributes like above in my code and I am not supposed to change the structure.

Is there any alternative way to write above code so that IE will understand it?

Thanks.

Upvotes: 0

Views: 4285

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Updated Answer based on question edit:

You're using an identifier you really should stay away from: Object. I would recommend changing both the id and the name of the variable you use. So:

<div id="theObject" titleDiv="blank"></div>

and

var theObject=document.getElementById('theObject');
theObject.setAttribute("titleDiv","myDiv");

Object is a built-in function in JavaScript. Since the id of elements gets dumped into the global namespace, I would avoid using any of the built-in JavaScript functions (Object, Function, Date, etc.) as id values. For similar reasons, not least just so you're not confusing yourself and others, I would stay away from them as variable names.

That said, I couldn't replicate the problem (source), so although I would still change the id and variable name, that may not be the problem. See also below.


Original Answer:

You call setAttribute on the DOM element instance. You don't do it via the built-in Object function.

If you use a DOM element, it works (even on IE9):

(function() {
  // Get an actual DOM element
  var target = document.getElementById("target");

  // Set the attribute
  target.setAttribute("titleDiv","myDiv");

  // Show the result
  display("Result: " + target.getAttribute("titleDiv"));

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }
})();

Live Example | source

If you use the F12 developer tools and go to the HTML tab, you can see that the div does actually get the attribute. (Be sure to use dev tools, not "view source" -- "view source" will show you the HTML that was sent from the server, not the current state of the DOM.)


Side note: Using nonstandard attributes that don't use the data- prefix is a bad idea. You might want to feed that information up the chain to whoever is dictating this. But that's almost certainly not the problem you're having.

Upvotes: 3

Related Questions