-1

I have a list of class names. I want to know which class has background image. how can I do that using javascript.

Suppose I have classes in css

.class1 {
   background-image = url("someurl");
   some attributes
}
.class2 {
   some attributes
}

I have only array of class name

arr = ["class1", "class2"]

Here is code what I am doing in javascript

element  = document.getElementsByTagName('*');
for(var i = 0; i < element.length; i++){
   var C = element[i].className;
   var arr = C.split(' '); //because an element can have more classes and any of them can have background image
   for(var j = 0; j < arr.length; j++){
      var clas = arr[j];
      // here I want something that can find clas has background image or not
   }
}

Thanks in advance.

  • 4
    Why do you want to know? This sounds like an XY problem ( http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem ) – Dai Feb 04 '15 at 06:18
  • 1
    You want to find out which classes, in the stylesheet, have background-images set? Or which classes, of the elements on the page, have background-images set? – David Thomas Feb 04 '15 at 06:21
  • @David which classes, of the elements on the page, have background-images set – Rohit Kumar Feb 04 '15 at 06:42

1 Answers1

1

Though it really seems its an XY problem for you, but still you can know which class has a background-image set. see http://jsfiddle.net/z3uLt1ea/,

$(function(){
   arr = ["class1", "class2"];
    arrBgExists=[];
    $(arr).each(function(i,ele){

        var exists=$('.'+ele).css('background-image');
        console.log(exists)
        if(exists!='none'){
            arrBgExists.push(ele);
        }

    });

console.log('these elements are having background'+arrBgExists);    
})

I have used Jquery here( and here is the pure javascript version).

Please Note: css classes are actually html classes(I mean they are defined when you create an html element with that class) read this answer from BoltClock,

so my solution is only valid when you have defined elements with classes you want to find out(example situation), else there is no solution

Community
  • 1
  • 1
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88