Home > OS >  Why style.backgroundImage returns empty?
Why style.backgroundImage returns empty?

Time:10-02

So here is the HTML

<button >w</button>
<script src="index.js" charset="utf-8"></script>

And This is the CSS

.w {
  background-image: url("images/tom1.png");
}

.a {
  background-image: url("images/tom2.png");
}

.s {
  background-image: url("images/tom3.png");
}

.d {
  background-image: url("images/tom4.png");
}

.j {
  background-image: url("images/snare.png");
}

.k {
  background-image: url("images/crash.png");
}

.l {
  background-image: url("images/kick.png");
}

Lastly this is the javascript

for (let i in document.querySelectorAll(".drum")) {
    document.querySelectorAll(".drum")[i].addEventListener("click", handleClick);
}

function handleClick() {
    var url = this.style.backgroundImage;
    console.log(url);
}

So when I click on w / a / s / d / etc. button, Console should return the image url right?

But this is what happened...

Console log shows empty string

Why is it empty??? Plz help

CodePudding user response:

Use NodeList.prototype.forEach() and Window.getComputedStyle

const handleClick = (evt) => {
  const url = getComputedStyle(evt.currentTarget).backgroundImage;
  console.log(url);
}

document.querySelectorAll(".drum").forEach((elDrum) => {
  elDrum.addEventListener("click", handleClick);
});

CodePudding user response:

As shown in the demo snippet, you need to use getComputedStyle to get the background image url when it is applied via css. Yet, if it is added directly to the element with the style attribute then you can get the value back from style.

Demo

document.querySelectorAll(".container div").forEach(function(item) {

  const styles = window.getComputedStyle(item);

  console.log(
    item.id, 
    item.style.backgroundImage || "none",
    styles.getPropertyValue("background-image") || "none"
  );
  

});
.container div {
  height: 200px;
  width: 200px;
  margin: 10px;
  display: inline-block;
}

.background {
  background-image: url(https://picsum.photos/200)
}
<div >
  <div id="1" ></div>
  <div id="2" style="background-image: url(https://picsum.photos/200)"></div>
</div>

  • Related