Alp
Alp

Reputation: 29739

Retrieve and modify :before element with jQuery

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?

Upvotes: 4

Views: 8811

Answers (3)

Baro
Baro

Reputation: 5520

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>

Upvotes: 1

aaberg
aaberg

Reputation: 2273

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

Upvotes: 5

Tim
Tim

Reputation: 9489

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.

Upvotes: 2

Related Questions