kylie2675647
kylie2675647

Reputation: 153

Find/Replace content in CSS pseudo-elements

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.

Upvotes: 0

Views: 188

Answers (2)

多一点点爱
多一点点爱

Reputation: 1363

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')

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 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.

Upvotes: 1

Related Questions