15

Given html such as :

<div data-points="800">Jonh</div>
<div data-points="200">Jack</div>
<div data-points="1200">Julian</div>

How to select elements were the value is superior to 1000 (x>1000) ?

Preference : via CSS selectors. If no such thing, then I will re-ask for a JQuery / JS answer.


Eventually used :

var x = 1000;
$("div").each(function() {
    if ($(this).attr('data-points') > x) {
        $(this).addClass('larger-than-x'); // Or whatever
    }
});
Hugolpz
  • 17,296
  • 26
  • 100
  • 187

1 Answers1

25

With CSS you can select elements with their attributes:

div[data-points] {  }

or the value of their attributes:

div[data-points="800"] {  }

but you can't use conditions in CSS.
I would recommend you to use a javaScript solutions for this problem which can be so easy, for example, using jQuery you can do something like:

$("div[data-points]").each(function() {
    if ($(this).attr('data-points') > 1000) {
        $(this).addClass('larger-than-1000'); // Or whatever
    }
});
Farid Rn
  • 3,167
  • 5
  • 39
  • 66
  • This is the only way to do it but at this point you may as well manually add the class IMO – Zach Saucier Jun 11 '14 at 23:04
  • Cool. Would do a great combo with localStorage. I validate the answer as it seems to be the only way to proceed :] – Hugolpz Jun 12 '14 at 21:03
  • 7
    They should add a selector for this, IMO. – Yuval A. Jul 14 '16 at 12:58
  • 1
    How would such a selector even work? You'd have to assume the value is always numeric. What if the value reflected in the markup isn't numeric? Also, what if the value *in the selector* isn't numeric? Should it match nothing, or be invalid? These are all things you have to consider when proposing a selector. – BoltClock Feb 03 '17 at 11:45
  • 1
    @BoltClock I just proposed a simple solution to a question that wanted to check the numbers. In real life you always have to validate the attribute selection results. – Farid Rn Feb 04 '17 at 12:52
  • My bad, I was talking to Yuval A. but didn't want to ping them over something like this. – BoltClock Feb 09 '17 at 04:12
  • @YuvalA. Yet another way **CSS is an abomination.** Perfectly reasonable feature and it can only be implemented by a standards committee. – Bob Stein Jun 11 '19 at 19:48