4

I want to select an element which was created by the CSS selector :before.

I tried it by using $('#element:before'), but that did not work, because it selected the whole element and not only the :before element.

Here is the sample code: DEMO

In that example, only the string "1. " should be red, not the whole string. Any idea how to do this?

Alp
  • 29,274
  • 27
  • 120
  • 198
  • 1
    `:before` doesn't create an element, so you can't select it. You can do this though http://jsfiddle.net/qGStB/2/ – Esailija Jun 17 '12 at 12:52
  • possible duplicate of [Manipulating CSS :before and :after pseudo-elements using jQuery](http://stackoverflow.com/questions/5041494/manipulating-css-before-and-after-pseudo-elements-using-jquery) – Rob W Jun 17 '12 at 13:11

3 Answers3

5

JQuery cannot set css properties on :before content, since it is not contained in an element. If you want to be able to manipulate the color of the :before content with javascript, you can create an extra css class, and add/remove this class.

example

aaberg
  • 2,253
  • 15
  • 14
  • if i follow your approach and assumed that the color can have 100 different values, i'd need to create 100 css classes. that does not feel very elegant. – Alp Jun 17 '12 at 13:14
  • 1
    That is correct. If you really have to be able to set a lot of different values, you cannot use the css content and css :before selector. Consider using a span element instead, this will give you much more control. – aaberg Jun 17 '12 at 13:29
  • I agree with @aaberg a span element is much nicer in this case. – Tim Jun 18 '12 at 07:56
2

You can't target the content created with css :before. You can however target a data element and add that to the content tag in css. See for this the accepted answer on this question.

Also styling with css is possible if you want that is your goal:

div:before {
    content: '1. ';
    color:red;
}

Will only make the 1. red.

Community
  • 1
  • 1
Tim
  • 9,351
  • 1
  • 32
  • 48
  • the css-only solution is not an option because i need to change the attribute (in this example the color) dynamically. therefore there is the need for some jquery magic. the `attr()` method does not seem to work with other attributes than with content, which is not useful in this case. – Alp Jun 17 '12 at 13:03
1

A way can be the custom properties, practically css variables.

Here the compatibilities

Here a bit of documentation

And an example where the variable --myColor have a global scope because declared under :root:

setInterval(function() {  
  
  $(':root').css('--myColor', 'red');

}, 2000);
:root {
  
  --myColor: green;
  
  font-size: 30px;
  font-weight: bold;
}
div:before {
    content: '1. ';
    color: var(--myColor);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  test
</div>
Baro
  • 5,300
  • 2
  • 17
  • 39