Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a CSS property to an HTML

I’m trying to listen for a click event on a node list to add a CSS property, I don’t want two nodes to have the property and I also want to toggle the CSS property on any of the node list with a second click, I can’t seem to get the right guard clause to use, any Help.

enter code here

const action = document.querySelectorAll ('.item');

const clearColor = function() {
  action.forEach(function(item) {
    item.classList.remove('item-color');
  })
}

action.forEach(function(item) {
  item.addEventListener("click", function(e) {
    const target = e.target; 
    clearColor();
    target.classList.toggle("item-color")
  })
})
.hidden {
  display: none;
}

.item {
  margin: 10px;
}

.item-color {
  background-color: red;
}
<div class="action">
  <div class="item">pizza</div>
  <div class="item">rice</div>
  <div class="item">spaghetti</div>
  <div class="item">honey</div>
  <div class="item">cheese</div>
</div>
**strong text**

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is the solution I came up with. Not the best but gets the job done.

const action = document.querySelectorAll ('.item');

const clearColor = function() {
  action.forEach(function(item) {
    item.classList.remove('item-color');
  })
}

action.forEach(function(item) {
  item.addEventListener("click", function(e) {
    const target = e.target; 
    if(target.classList.contains("item-color")){
        clearColor();
    }else{
        clearColor();
        target.classList.toggle("item-color")
    }
  })
})
.hidden {
  display: none;
}

.item {
  margin: 10px;
}

.item-color {
  background-color: red;
}
<div class="action">
  <div class="item">pizza</div>
  <div class="item">rice</div>
  <div class="item">spaghetti</div>
  <div class="item">honey</div>
  <div class="item">cheese</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading