jimmykup jimmykup - 2 months ago 11
Javascript Question

How can I find the background image of a clicked element (or the nearest child or parent element that has a background image) using JavaScript?

I'm writing a Chrome extension that I want to use to provide the user with the URL of a background image using Chrome's right-click context menu.

Right now my problem is finding the background image. If a user right-clicks the correct element then it's easy. But if they click a child of that element then I have to look at the parents. What's the most efficient way to handle this?

Some notes: I'm not injecting jQuery with my extension. And I've also thought of the scenario where an element that is absolutely positioned above the desired background image would get in the way. But I'm not concerned with that at the moment.

Here is my code so far. It works as long as the clicked element has a

. Failing to find one, it does not look at the parents yet.

document.body.addEventListener('contextmenu', function(ev) {

// get computed style
var style = window.getComputedStyle(ev.target, false);

// img src is inside 'url(' + ')' - slice those off
var src = style.backgroundImage.slice(4, -1);


return false;
}, false);


Here is a function that recursively looks up the DOM tree for a background image (you may want to tweak it to use computed styles if that is what you want):

function getBackgroundImage(el) {
    if (el == null) {
      return null;

    if (el.style.backgroundImage !== '') {
      return el.style.backgroundImage.slice(4, -1);
    } else {
      return getBackgroundImage(el.parentElement);

In your case you could just call it with the target:

var backgroundImage = getBackgroundImage(ev.target);