JSFiddle - React, Tailwind, and code Playground

by Abhishek Kumar

HTML

<div class="grid-container">
  <div class="grid-item">Cell 1 <button class="expand">+</button></div>
  <div class="grid-item">Cell 2 <button class="expand">+</button></div>
  <div class="grid-item">Cell 3 <button class="expand">+</button></div>
  <div class="grid-item">Cell 4 <button class="expand">+</button></div>
</div>

CSS

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.grid-item {
  background: lightblue;
  padding: 10px;
}

.expand {
  float: right;
}

.expanded {
  grid-column: span 2;
}

JavaScript

// Get all the expand buttons
let buttons = document.querySelectorAll(".expand");

// Loop through them and add a click event listener
buttons.forEach(function(button) {
  button.addEventListener("click", function() {
    // Get the parent grid item of the clicked button
    let item = button.parentElement;
    // Toggle the expanded class on the item
    item.classList.toggle("expanded");
    // Update the button text
    button.textContent = item.classList.contains("expanded") ? "-" : "+";
  });
});