0

I'm trying to get div imageBackground in Javascript.

function addToCartDialog(item) {
  img = item.getElementsByClassName("img")[0].style.backgroundImage;
  console.log(img);
}
.container div.item .img {
  background-image: url("https://burgersbar.co.il/wp-content/uploads/2018/12/המבורגר-פריט.png");
  background-size: cover;
  width: 240px;
  height: 180px;
  margin: 0 auto;
  cursor: pointer;
  display: block;
}
<div class="item" id="burger" onclick="addToCartDialog(this)">
  <div class="img">s</div>
  <div class="itemName">Spicy</div>
  <div class="info">100% meat</div>
  <div class="price">50₪</div>
</div>

Eveything looks fine on the page but when I click the div I get empty line in the console.. I can see the image on the page

Ajith Gopi
  • 1,509
  • 1
  • 12
  • 20
  • The `.style` property only gets you the properties defined in the `style` attribute from the markup (or if you've changed them by hand). You need `window.getComputedStyle()` for this – Andreas Apr 09 '21 at 16:06

1 Answers1

0

You can use getComputedStyle() to extract the properties bonded to an element from external style sheets or non-inline CSS.

function addToCartDialog(item) {
  //Get the propert using computedStyleMap()
  img = item.getElementsByClassName("img")[0].computedStyleMap().get("background-image").toString();
  //Extract the URL using regular expression
  image_url = img.match(/.+?\"(.+?)\".+/)
  console.log(image_url[1]);
}
.container div.item .img {
  background-image: url("https://burgersbar.co.il/wp-content/uploads/2018/12/המבורגר-פריט.png");
  background-size: cover;
  width: 240px;
  height: 180px;
  margin: 0 auto;
  cursor: pointer;
  display: block;
}
<div class="container">
  <div class="item" id="burger" onclick="addToCartDialog(this)">
    <div class="img">s</div>
    <div class="itemName">Spicy</div>
    <div class="info">100% meat</div>
    <div class="price">50₪</div>
  </div>
</div>

PS: I have added a .container div for reference

Ajith Gopi
  • 1,509
  • 1
  • 12
  • 20