Muhammed Saifudeen
Muhammed Saifudeen

Reputation: 23

Get the CSS background image path using JavaScript

can you please explain, how can i get the correct path of styles of html element that has been added through css (eg, background:ulr()) using javascript or jQuery.

var img = document.querySelectorAll('*');
img.forEach(function(i){
   var imageSrc = new Image(); 
     i.addEventListener("mouseover", function(e){

      if(i.style.background){

        }
    })
});

can the i.style.background find the correct css DOM path? i've added a fiddle. https://codepen.io/saifudazzlings/pen/VQvooy

Upvotes: 2

Views: 1015

Answers (1)

Christian Santos
Christian Santos

Reputation: 5456

HTMLElement.style will only give you the result of the inline styles of an element. If you need to get the styles that have been computed from an external stylesheet, you need to use Window.getComputedStyle:

var bgImage = window.getComputedStyle(i).backgroundImage;

See the updated codepen here using Window.getComputedStyle. The background image URL is printed when you hover over the div with the background.

Upvotes: 3

Related Questions