CSS Selector compare 2 attributes

前端 未结 2 521
花落未央
花落未央 2021-01-24 18:15

I\'m looking for a way to build a selector that would match where two attributes have the same value, but can\'t find a syntax. Is this possible? How?

What I hoped would

2条回答
  •  攒了一身酷
    2021-01-24 18:41

    This is not possible with standard CSS.

    Although you hadn't exactly asked "Well in that case, what can I do?", leaving this answer on its own feels completely insufficient, so here's also a jQuery solution for something that might do the trick.

    Assuming you are looking for divs only, the code below will work. Otherwise, you can edit the selector in the first line of the jQuery to be something other than $("div")

        $("[data-valueA]").each(function() {
            $this = $(this);
            var firstAttr = $this.data("valuea");
            var secondAttr = $this.data("valueb");
            if (firstAttr == secondAttr) $this.addClass("redBackground");
        });
      div {
          padding: 20px;
          margin: 20px;
          border: 1px solid black;
      }
      
      .redBackground {
          background-color: red;
      }
    
    
    ValueA and ValueB match
    ValueA and ValueB do not match

提交回复
热议问题