silverwind
silverwind

Reputation: 3915

Retrieve .textContent including pseudo elements

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/

Upvotes: 4

Views: 1075

Answers (2)

silverwind
silverwind

Reputation: 3915

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;
}

Upvotes: 3

fippli
fippli

Reputation: 1

This doesn't get the rendered text but it imitates the behavior and produces the same string:

Step 1: Get the parent div

Step 2: Map through the children of the parent to get the text in an array

Step 3: Join the array to a string

<div id="parent"><span>first</span><span>second</span></div>

const parent = document.getElementById("parent");
const childTextArray = [...parent.childNodes].map(child => child.innerText);
// => ["first", "second"]
const theStringYouAskedFor = childTextArray.join(", ");
// => "first, second"

Upvotes: -1

Related Questions