javascriptjqueryweb-developer-toolbar

Change the fill color for multiple tags using jQuery


<rect class="day" fill="#fbedf0" data-count="0"></rect>
<rect class="day" fill="#cqe45b" data-count="0"></rect>

I'm trying to edit the values of the fill color for multiple tags using jQuery.

I'm able to iterate through all the rect tags and get their fill values, but am not able to change them using the css() function, and gives an error saying that the read css property of null

for(let i=0; i<rect.length; i++){
  if(rect[i].getAttribute("fill") === "cqe45b"){
    $('rect[i]').css({fill:"#2038fb"});
  }
}

What I essentially need is that, if the fill color is #cqe45b, I want to change it to #2038fb and if it were #cbedf0, I want to make it #c7ef80

UPDATE: I'm trying to perform this function on a third-party website which doesn't allow the import of jQuery, so, is there any way to go around this?


Solution

  • Get all rect.day[fill="#cqe45b"] elements, and use .attr() to set the fill attribute's value.

    $('rect.day[fill="#cqe45b"]').attr("fill", "#2038fb");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <svg viewBox="0 0 300 50" xmlns="http://www.w3.org/2000/svg">
      <!-- Simple rect element -->
      <rect class="day" fill="#fbedf0" x="0" y="0" width="50" height="50" />
    
      <!-- Rounded corner rect element -->
      <rect  class="day" fill="#cqe45b" x="120" y="0" width="50" height="50" rx="15" ry="15" />
    </svg>

    And you can replace jQuery with document.querySelectorAll(), and Element.setAttribute().

    Note: NodeList.forEach() is not supported by IE. You can replace it for a for loop if you need to support IE.

    document.querySelectorAll('rect.day[fill="#cqe45b"]')
      .forEach((el) => {
        el.setAttribute("fill", "#2038fb")
      });
    <svg viewBox="0 0 300 50" xmlns="http://www.w3.org/2000/svg">
      <!-- Simple rect element -->
      <rect class="day" fill="#fbedf0" x="0" y="0" width="50" height="50" />
    
      <!-- Rounded corner rect element -->
      <rect  class="day" fill="#cqe45b" x="120" y="0" width="50" height="50" rx="15" ry="15" />
    </svg>