Search code examples
javascripthtmlimagemap

Why does getElementById on image map area not return the area element in IE?


I have an image map on a web page with the following HTML:

<div class="container">
    <img src="image.png" usemap="#hotspots">
    <map name="#hotspots">
        <area id="seg-1" href="" shape="poly" coords="167,286,113,379,320,379,266,286,167,286"/>
        <area... />
        <area... />
        <area... />
        ...
    </map>
</div>

And I'm trying to get a reference to an area element with the following JavaScript:

var seg1 = document.getElementById("seg-1");

I successfully get the reference in:

  • Safari 6 (OS X)
  • Chrome 26 (OS X)
  • Firefox 21 (OS X)
  • Chrome 27 (XP)
  • Chrome 27 (W7)
  • Chrome (W8).

But not in:

  • IE8 (XP)
  • IE9 (W7)
  • IE10 (W8)
  • Firefox 17 (XP)
  • Firefox 21 (W7)
  • Firefox 21 (W8).

When it works I get a reference to the HTML area element, but when it doesn't work I get a reference to the document. Here are the console log messages:

Working:

HTMLAreaElement

Not working:

http://localhost/index.html

I know how to work around this, but I'm trying to understand why this is happening? Why does getElementById not work for image map area elements?

Thanks for any of your thoughts.


Solution

  • It seems this simply has to do with the "toString" method on the area element in those browers. For whatever reason, it prints the derived value of the href. However, that's just what gets printed. The actual result of getElementById is still the area element.

    For example, if you use console.log(document.getElementById('seg-1').shape) in those browsers, it will still correctly print "poly."