Given
<div><span>first</span><span>second</span></div>
and
span + span::before {
content: ', ';
}
I'd like to retrieve the rendered string 'first, second'
in JavaScript but .textContent
ignores the content of the pseudo-element as it's not part of the DOM. Is there a way to get the actual rendered text?
Example: https://jsfiddle.net/silverwind/nyr5kohj/2/
Got it working using getComputedStyle
. It does not support ::after
but that shouldn't be too hard to add.
let text = '';
for (const child of children(document.querySelector('div'))) {
if (child.nodeType === 1) {
const before = window.getComputedStyle(child, '::before').getPropertyValue('content');
if (before && before !== 'none') {
text += before.replace(/^['"]/, '').replace(/['"]$/, '');
}
} else if (child.nodeType === 3) {
text += child.textContent;
}
}
alert(text);
function children(node) {
const ret = [];
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
ret.push(child, ...children(child));
}
return ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With