Search code examples
javascriptdomoperamozilla

Defining img custom property


I'm trying to assign property "itemId" for DOM element "img"

Here is code

var img = document.createElement('IMG');
window.console.log(itemId);
img.itemId = itemId;
window.console.log(img.itemId); 

After execution console contains this messages:

41
http://example.domain/41

Where example.domain - is adress of my site.

This problem appears in Opera and Mozilla, but in Chrome this code works fine (img.itemId == 41). Example: http://jsfiddle.net/uwPY5/

Can anyone explain what's going on?


Solution

  • Very weird behavior, but try the standard way:

    img.setAttribute("itemId", itemId);
    

    To be compatible with HTML5 though, you should prefix your attribute name like this:

    img.setAttribute("data-itemId", itemId);
    

    Then to read it back:

    var itemId = img.getAttribute("data-itemId");