Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve .textContent including pseudo elements

Tags:

javascript

dom

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/

like image 669
silverwind Avatar asked Sep 06 '25 03:09

silverwind


1 Answers

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;
}
like image 197
silverwind Avatar answered Sep 09 '25 01:09

silverwind