Jun Jung
Jun Jung

Reputation: 405

I am trying to apply filter:brightness in JavaScript to a bunch of image elements

var brightness = document.getElementById("brightness");

trash.addEventListener("click", function() {
  brightness.style.filter = "brightness(100%)";

});
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<div id="trash">
  <i class="fas fa-trash"></i>
</div>

<img src="imgs/utensil.svg" alt="utensil" id="utensil" id="brightness">
<img src="imgs/straw.svg" alt="straw" id="straw" id="brightness">
<img src="imgs/chipbag.svg" alt="chip bag" id="chip_bag" id="brightness">
<img src="imgs/garbagebag.svg" alt="garbage bag" id="g_bag" id="brightness">
<img src="imgs/eggs.svg" alt="eggs container" id="egg_container" id="brightness">

Hi, I am sorry that I have to embed a series of svg files that do not exist. Is there any way to apply brightness through clicking the trash can icon to all 4 images without having to assign every img's id (untesil.style.filter = "brightness(100%);..and so on)? I made the second unified id, which is "brightness" but it does not seem to work.

Upvotes: 1

Views: 2858

Answers (1)

jscul
jscul

Reputation: 772

Like the other guy in the comments said, you need to use class... this works.

var trash = document.getElementById("trash");

trash.addEventListener("click", function() {
  var elems = document.querySelectorAll(".brightness");
  for (var i = elems.length; i--;) {
    elems[i].style.filter = "brightness(1.7)";
  }
});
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<div id="trash">
  <i class="fas fa-trash"></i>
</div>

<img src="imgs/utensil.svg" alt="utensil" class="brightness">
<img src="imgs/straw.svg" alt="straw" class="brightness">
<img src="imgs/chipbag.svg" alt="chip bag" class="brightness">
<img src="imgs/garbagebag.svg" alt="garbage bag" class="brightness">
<img src="imgs/eggs.svg" alt="eggs container" class="brightness">

Upvotes: 3

Related Questions