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

3
  • Try using style.backgroundImage (note the capital i in image) Commented Sep 17, 2017 at 21:19
  • I tried it and got this error Uncaught TypeError: Cannot read property 'backgroundImage' of undefined Commented Sep 17, 2017 at 21:21
  • 1
    Possible duplicate of Can I get div's background-image url? Commented Sep 17, 2017 at 21:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.