Active class for single class element jQuery

20 Views Asked by At

I have these buttons which are actually p elements in a grid and they all have the same class. I would like to change the color of the p element which the user clicks on. How can I add an active class in jQuery and do so in a way that it only selects one of the elements in said class? Btw I have various "grids" in my html all configured the same way...(hence class grid :-D)

Thanks!

image of buttons

jquery variable

 const $size = $(".size");

 <div id="red-details" class="extra-details">
          <p>
            The ultimate in style and comfort, the Red Flyer's are great for
            walking and casual wearing.
          </p>

          <h3>Size</h3>
          <div class="grid">
            <p class="size">7</p>
            <p class="size">8</p>
            <p class="size">9</p>
            <p class="size">10</p>
            <p class="size">11</p>
          </div>
          <button class="add-to-cart">Add To Cart</button>
        </div>

1

There are 1 best solutions below

0
Paul T. On BEST ANSWER

One way, is to have a specified CSS. Have handling to remove the style from any <p> element (based on your example) that has the CSS applied, and then set the CSS to the clicked element, so that only 1 has the applied style.

Try the runnable example below. In the example, I used CSS for a .clicked style, but you can rename this as desired.

$(document).ready(function() {
    $('p').on('click', function(e) {
      // Any <p> that has the clicked CSS, remove it:
      $('p.clicked').removeClass('clicked');
      
      // Then apply the CSS to the clicked element
      $(this).addClass('clicked');
    })
});
.clicked {
     background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="red-details" class="extra-details">
      <p>
        The ultimate in style and comfort, the Red Flyer's are great for
        walking and casual wearing.
      </p>

      <h3>Size</h3>
      <div class="grid">
          <p class="size">7</p>
          <p class="size">8</p>
          <p class="size">9</p>
          <p class="size">10</p>
          <p class="size">11</p>
      </div>
  <button class="add-to-cart">Add To Cart</button>
</div>