skip to Main Content

Probably a silly question, but the basic way I learned how to change CSS of something on click is

var x = document.getElementById("id"); 
    x.style.height = "auto"; 

or whatever.

But say I want divs of a certain class to change CSS attributes when clicked. But not all at the same time, only the one I just clicked. Adding separate ID’s and functions to each of them seems irrational.

Thank you!

2

Answers


  1. In order to change the CSS of individual elements when clicked without assigning separate IDs and functions, event delegation can be used with JavaScript. This means you have one event listener attached on a parent element that takes care of clicks on its child elements.

    Example:

    document.querySelector('.container').addEventListener('click', function() {
      if (event.target.classList.contains('div')) {
        event.target.classList.toggle('clicked');
      }
    });
    .div {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      margin: 10px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    /* Style to apply on click */
    .clicked {
      background-color: lightgreen;
      height: auto;
    }
    <div class="container">
      <div class="div">Div 1</div>
      <div class="div">Div 2</div>
      <div class="div">Div 3</div>
    </div>
    Login or Signup to reply.
  2. The document.querySelectorAll() would perhaps be the most canonical way to achieve that. Simply select your elements by their class name and attach an event listener to each element.

    const list = document.querySelectorAll('.list');
    if(list.length){
       for (let l of list){
          l.addEventListener('click', (e)=>{
            l.classList.toggle('completed')
          })
       }
    }
    .list{
       font-family: Arial, Helvetica, sans-serif;
    }
    .completed{
       text-decoration: line-through;
       opacity: 0.5;
    }
    <ul>
      <li class="list">Pick up Milk</li>
      <li class="list">Walk Dog</li>
      <li class="list">Get dub in CoD</li>
      <li class="list">Beer O'Clock</li>
    </ul>

    If you didn’t want to toggle a class and target only a single specific attribute you can do that too:

    const bars = document.querySelectorAll('.bar');
    if(bars.length){
       for (let b of bars){
          b.addEventListener('click', (e)=>{
            b.style.width = `${e.target.offsetWidth + 10}px`;
          })
       }
    }
    .bar{
       width: 100px;
       height: 30px;
       background: red;
       margin: 4px 0;
    }
    .bar:nth-child(even){
      background: blue;
    }
    <section>
       <div class="bar"></div>
       <div class="bar"></div>
       <div class="bar"></div>
       <div class="bar"></div>
    <section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search