Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compare two attributes in a CSS selector?

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 work:

[data-valueA=data-valueB]

When I know valueA and valueB ahead of time, I could do:

[data-valueA="knownValueForA"][data-valueB="knownValueForB"] {}

But I don't know the values and aren't concerned with them in this case, just knowing when they are the same.

Here's a fiddle to explore with: https://jsfiddle.net/rainabba/m49e4e7k/

To clarify, I'm looking for a pure CSS solution.

like image 521
rainabba Avatar asked Oct 29 '25 18:10

rainabba


1 Answers

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;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-valueA="MyValue" data-valueB="MyValue">
    ValueA and ValueB match
</div>

<div data-valueA="XXX" data-valueB="YYY">
    ValueA and ValueB do not match
</div>
like image 147
Tyler Roper Avatar answered Oct 31 '25 08:10

Tyler Roper