0

I'm having issues with this code, its working on all the browsers except IE.

THE HTML

<div class="separator">
<a href="http://www.domain.com/images/s1920/original.jpg">
<img height="250" src="http://www.domain.com/images/s400/photo.jpg" />
</a>
</div>

THE JAVASCRIPT

<script type='text/javascript'>
var ImageSource = document.getElementsByClassName('separator')[0].getElementsByTagName('a')[0].href;
ImageSource = ImageSource.replace(/0\//, '0-d/');
</script>

It works as expected but when i tested on IE it returns this error,

Message: Object doesn't support this property or method

What could be the problem?

Spudley
  • 166,037
  • 39
  • 233
  • 307
33_____________
  • 45
  • 1
  • 1
  • 10

2 Answers2

6

.getElementsByClassName is not supported in IE8 or earlier.

You can use .querySelector() instead, which does work in IE8, and all other modern browsers.

var ImageSource = document.querySelector('.separator').getElementsByTagName('a')[0].href;

Note that querySelector() returns a single element (hence there isn't a [0] after it in the code above). You only need one element in the given example, but if you want multiple elements, the same as .getElementsByClassName(), then you can use .querySelectorAll().

Also note that all the above only applies for IE8 and later. If you need to support IE7, then then you'll have to find another solution. Probably your best option would be jQuery since IE7 doesn't have a native solution built-in.

Hope that helps.

Spudley
  • 166,037
  • 39
  • 233
  • 307
2

well if you are using IE8 so getElementsByClassName is not supported

see http://caniuse.com/getelementsbyclassname

Ali
  • 595
  • 4
  • 13
  • 42