Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS data attribute conditional value selector?

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
    }
});
like image 461
Hugolpz Avatar asked Jun 11 '14 22:06

Hugolpz


People also ask

What is attr () in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

How can we select elements with a specified attribute in CSS?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How do I style a data attribute in CSS?

To use this selector, add a pipe character (|) before the equals sign. For example, li[data-years|="1900"] will select list items with a data-years value of “1900-2000”, but not the list item with a data-years value of “1800-1900”. Value ends with: attribute value ends with the selected term.

What CSS selector is used to select elements with a specified attribute and value?

The [attribute=value] selector is used to select elements with the specified attribute and value.


1 Answers

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
    }
});
like image 156
Farid Rn Avatar answered Sep 24 '22 18:09

Farid Rn