0

I'm trying to get the background url of the image. below is the code from the webpage

<style type="text/css">
             .great-banner.live-banner { 
             background-image:
                 url("urloftheimage");
             }
            </style>
   <div class="great-banner live-banner">
   </div>

I tried using

document.getElementsByClassName(".great-banner.live-banner").style.backgroundimage

window.getComputedStyle(document.getElementsByClassName(".great-banner.live-banner"),false); but both of these didn't work form me

I also tried

window.getComputedStyle(document.getElementsByClassName('.great-banner.live-banner')[0], null).getPropertyValue('background-image').split(/'|"/)[1]; and i'm getting the below error

Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

Can you please help me how to get the background image URL

Siva
  • 1,078
  • 4
  • 18
  • 36
  • Try using style.backgroundImage (note the capital i in image) –  Sep 17 '17 at 21:19
  • I tried it and got this error Uncaught TypeError: Cannot read property 'backgroundImage' of undefined – Siva Sep 17 '17 at 21:21
  • 1
    Possible duplicate of [Can I get div's background-image url?](https://stackoverflow.com/questions/8809876/can-i-get-divs-background-image-url) – Temani Afif Sep 17 '17 at 21:28

2 Answers2

1

First of all document.getElementsByClassName will return a collection of elements, so there is no style property. - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Secondly, the argument you pass to the function should be a class name, not a css selector. Maybe you are looking for querySelectorAll - https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Try document.querySelectorAll(".great-banner.live-banner")[0].style.backgroundImage instead

Hugo Silva
  • 6,748
  • 3
  • 25
  • 42
0

I found the solution:

window.document.defaultView.getComputedStyle(document.getElementsByClassName('great-banner live-banner')[0], null).getPropertyValue('background-image').split(/'|\"/)[1]; in java script. It will return the URL.

While using in selenium:

JavascriptExecutor jsExec = (JavascriptExecutor) driver; jsExec.executeScript("return window.document.defaultView.getComputedStyle(document.getElementsByClassName('great-banner live-banner')[0], null).getPropertyValue('background-image').split(/'|\"/)[1];"));

Add 'return' in the script as per the above line while using in selenium otherwise, it will provide null value

Siva
  • 1,078
  • 4
  • 18
  • 36