0

I'm trying to modify an existing webpage by inserting my own Javascript file in it. I'm setting a background Image for this webpage by inserting a new Div through my Javascript and setting background of that div to image url. For centering this image on background and to make it occupy the whole webpage, I'm using

'background-size': 'cover'

property. This of course doesn't work in older IE versions.

I want to fix it, I'm thinking of zooming in the image by specific ratio calculated using page height/width and image height/width.

So I want to detect if browser is IE. I checked the webpage and it has this code that detects browser and add's a div with class IE.

<!--[if lte IE 5]>
  <div class="ie">
<![endif]-->
<!--[if IE 6]>
  <div class="ie ie6">
<![endif]-->
<!--[if IE 7]>
  <div class="ie ie7">
<![endif]-->

My questions is how do I detect if this page has a div with class ie. Also, I would really appreciate if someone could suggest an alternative way of setting a background image on the webpage page that occupies it fully irrespective of dimensions of image/page and image center is focused.

sublime
  • 4,013
  • 9
  • 53
  • 92
  • 2
    why do you need JS to detect the IE class? Why not target the element in the stylesheet? with div .ie {different style here}. Also for background-size specifically you can use a filter as discussed here http://stackoverflow.com/questions/2991623/make-background-size-work-in-ie – aroundtheworld Mar 23 '13 at 02:45

3 Answers3

2

You'd have to loop through all of the <div> elements on the page, until one matches the className you are looking for. Something like:

var div = document.getElementsByTagName('div');
for(i=0; i<div.length; i++) {
    if(div[i].className.match(/(^|\s)ie(\s|$)/)) {

        // Code to Do your IE Stuff Here

        break;
    }
}
Ross McLellan
  • 1,872
  • 1
  • 15
  • 19
1
document.addEventListener("DOMContentLoaded", function() {
  var ie = document.getElementsByClassName("ie");
  if(ie.length > 0) {
    alert("It's IE!");
  }
}

This should answer your first question, although I agree that there are better solutions for your overall goal.

Appleshell
  • 7,088
  • 6
  • 47
  • 96
0

If you load the jQuery library in your page, which you can link from the Google CDN, this is a very simple matter.

CDN: https://developers.google.com/speed/libraries/devguide#jquery

Usage: $("div.className").first()

Otherwise this will require some more effort ... the best possible way to deal with this is add an id attribute to the div element like so:

<div id="myElement"></div>

And then use the document.getElementById function to retrieve your div tag.

document.getElementById('myElement');

To see if it has a specific class after this addition please refer to this other post: Test if an element contains a class?

Community
  • 1
  • 1
Travis Sharp
  • 821
  • 11
  • 26