0

Trying to find some text that is content produced by a ":before" pseudo-element.

And then I would like to change the css of that content.

Is this even possible? Here's what I have.

Thanks.

var $test = $('.test').html();
$test = $test.replace(/one/gi, '<span class="red">one</span>');
$test = $test.replace(/two/gi, '<span class="green">two</span>');
$test = $test.replace(/three/gi, '<span class="blue">three</span>');
$('.test').html($test);
.test:before { content: 'one two three';}

.red {color: red;}
.green {color: green;}
.blue {color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="test"></div>

Here is a fiddle.

kylie2675647
  • 153
  • 12
  • 1
    you cannot place html inside content of pseudo element – Temani Afif Dec 26 '19 at 13:56
  • What's wrong with adding the class the the element itself and then styling its `:before` pseudo-element? – Alon Eitan Dec 26 '19 at 13:57
  • 1
    Does this answer your question? [Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery](https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) – Mitya Dec 26 '19 at 13:57

2 Answers2

1

If you just want to replace the content with some html elements. You can try this way

var $test = $('.test');

// clear :before content data
$test.attr('data-before', '');

$test.append('<span class="red">one</span>');
$test.append('<span class="green">two</span>');
$test.append('<span class="blue">three</span>');
.test:before { content: attr(data-before);}

.red {color: red;}
.green {color: green;}
.blue {color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="test" data-before="one two three"></div>

It seems to be hacked. Because we don't really replace anything, just show and hide the content.

Tân
  • 1
  • 15
  • 56
  • 102
0

Get please use

#app::before { content: 'hello world!' }

var myIdElement = document.getElementById("app");
var beforeStyle = window.getComputedStyle(myIdElement, ":before");

console.log(beforeStyle.content) // hello world!

Set please use

<div id="app" data-text="hello world!"></div>

#app::before { content: attr(data-text) }

document.getElementById("app").setAttribute('data-text','new text')
多一点点爱
  • 1,333
  • 6
  • 12