Search code examples
javascriptjquerycsstampermonkeyuserscripts

How to get the url of a background-image


i was trying to get the url of background-image to use it in "userscript" but couldn't get it to work on this html code without adding class id

<div class="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url('https://www.example.com/image.png');"></div>

the result should be https://www.example.com/image.png

This is required result but want to achieve the same without getting by ID:

// Get the image id, style and the url from it
var img = document.getElementById('vjs-poster'),
  style = img.currentStyle || window.getComputedStyle(img, false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
alert('Image URL: ' + bi);
<div class="vjs-poster" id="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url(https://www.example.com);"></div>


Solution

  • An ID ensures you get a single element from the DOM, whereas getting by class you can get multiple instances.

    It's kinda bad practise to do what I'm about to show you, but given that there is only one instance of vjs-poster class you can get all instances of vjs-poster by CLASS, and select the first instance in the returned array where you'll be able to get the style.

    // Get the image id, style and the url from it
    var img = document.getElementsByClassName('vjs-poster'),
      style = img.currentStyle || window.getComputedStyle(img[0], false),
      bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
    
    // Display the url to the user
    alert('Image URL: ' + bi);
    <div class="vjs-poster" id="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url(https://www.example.com);"></div>

    Fiddle here: https://jsfiddle.net/r2bvdygs/