Palash Mondal
Code with Palash

Code with Palash

Get background image URL for any element using JavaScript

Get background image URL for any element using JavaScript

Palash Mondal's photo
Palash Mondal

Published on Feb 5, 2021

4 min read

Listen to this article

In this post, I’ll explain how to get background image URL for any element using JavaScript.

Getting Started

You can find the html & css code for this post in this repository.

In that repository, inside the src folder you can find three files:

  • index.html
  • style.css
  • scripts.js

Now, let me explain about each of them in details.

index.html

In this HTML file, we have our basic markup like this:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link href="style.css" rel="stylesheet">

    <title>Background-image URL</title>
  </head>
  <body class="mt-4">

    <div class="container">
      <h1 class="pb-3 mb-3 border-bottom">
        Get Background-image URL
      </h1>
      <div id="main" class="rounded my-4"></div>
      <small class="text-muted">
        Open console to view the output
      </small>
    </div>

    <script src="scripts.js"></script>
  </body>
</html>

So, this is a simple markup. It has some basic meta tags. I have also included bootstrap css for basic styling.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

Then I have referenced our style.css in the src folder using:

<link href="style.css" rel="stylesheet">

I will explain more about the content of style.css in the next section. Next, we have a simple title for the page. Then inside the body tag, we have parent div element like:

<div class="container">
    ...
</div>

Now, this container class is coming from bootstrap css, that we have included in this page, so you don't need to worry about implementing that. It is just there to add some basic styling to the page. Then, we have an h1 tag, a div and a small element.

<h1>
    Get Background-image URL
</h1>
<div id="main"></div>
<small>
    Open console to view the output
</small>

and finally, we have also referenced our scripts.js file in the src folder using:

<script src="scripts.js"></script>

style.css

The content of this style.css file is like this

#main {
  background-image: url("https://via.placeholder.com/200");
  width: 200px;
  height: 200px;
}

Here, we have simply added a background image to the div with id main and also added some width and height. Now, our main goal is to find this actual link mentioned inside url("....") as a string, which is https://via.placeholder.com/200 here using javascript.

scripts.js

Now, inside this repository scripts.js already has the finished code but let us assume it is empty for now and we will write our main logic from start to get the background image URL for the div with id main.

So, here are 4 steps that we need to do in order to achieve this.

1. Get the div element with id #main

In order to get an Element object representing the element whose id is main, we will use

const main = document.getElementById("main");

2. Get all CSS properties of the above element

Next, to get all the CSS properties of the above element, we will use window.getComputedStyle() method like:

const styles = window.getComputedStyle(main);

This will return an object containing the values of all CSS properties of the main element, after applying active stylesheets and resolving any basic computation those values may contain.

3. Get backgroundImage property from it

Now, as styles is an object here, so we can easily access the backgroundImage property using dot notation like:

const image = styles.backgroundImage;

Now, if we console log this image variable we will get the result like:

console.log( image )
➡ url("https://via.placeholder.com/200")

This is the exact same background-image url that we have mentioned in our style.css. So, we are getting very close to our target. Now we just need to remove url(" from start and ") from the end for this output string.

url("https://via.placeholder.com/200")  ❌
https://via.placeholder.com/200  ✔️

4. Finally, extract backgroundImage URL

So for this, we will simply use String slice() method

const url = image.slice(5, -2);

Here, the first parameter to the slice() method 5 means that it will ignore the first 5 characters in the image string and return the rest of the string. Then the second parameter to the slice() method 2 means that it will ignore the last 2 characters of string and return the rest of the string. Please note that slice()extracts the text from one string and returns a new string, without modifying the original string.

Now, if we finally console log this url variable we will get the background image URL for the div with id main.

console.log( url );
➡ https://via.placeholder.com/200

Wrap Up

I hope you will find this post useful and learn something new in the process. If you want to learn more HTML, CSS, JavaScript and web development tips & tricks, please make sure to subscribe on YouTube!

Did you find this article valuable?

Support Palash Mondal by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this