Doug
Doug

Reputation: 1515

Can CSS psuedo content pull the element's text?

<p class="test">Lorem Ipsum Dolor.</p>

Can a CSS psuedo-element's (:before/:after) content property pull from the DOM element's plain text?

.test:after{ content: html; }

With the result of...

 Lorem Ipsum Dolor.Lorem Ipsum Dolor.

Looking for a non-JavaScript solution (if one is possible).

Thanks :)

Upvotes: 1

Views: 317

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

No, it's currently not possible to retrieve the element's text and display it using the content property without using JavaScript. However, as I pointed out in the comments, you can use the CSS attr() function in order to retrieve the element's attribute value and display it.

For instance, you could add a custom data-content attribute to the element:

[data-content]:after {
  content: attr(data-content);
}
<p data-content="Lorem Ipsum Dolor."></p>

If you want to display the same string twice (as your question implies), you could simply use multiple attr() functions:

[data-content]:after {
  content: attr(data-content) ' ' attr(data-content);
}
<p data-content="Lorem Ipsum Dolor."></p>

If you use JavaScript, you could simply iterate over the elements and add a custom data-content attribute to the element(s) based on the textContent property of the element:

[].forEach.call(document.querySelectorAll('[data-content]'), function (element) {
  element.dataset.content = element.textContent;
});
[data-content]:after {
  content: ' ' attr(data-content);
}
<p data-content>Lorem Ipsum Dolor.</p>

<p data-content>Some other string.</p>

It's also worth mentioning that the content property's value is still rendered as a string (and not HTML).

Upvotes: 2

Related Questions