0

<span class="SpellingError SCXO166867203 BCX8" style="margin:0px;padding:0px;background-repeat:repeat-x;background-position:left bottom;">bv</span><span class="NormalTextRun SCXO166867203 BCX8" style="margin:0px;padding:0px;background-color:inherit;">.</span>

Does anybody know what clean-up code I could write in Javascript so "bv" and "." can be read together and not in separate (span) elements? I have a Js function that should wrap the "bv." within highlighting marks/tags, but the different span elements prevent the text "bv." to be read together. Is there a simple way to automate the removal of div or span class attributes for example, including when they are nested?

1 Answer 1

1

Yeah, you can handle that pretty cleanly with a small DOM cleanup script. Basically, what’s happening is that your text is split across multiple spans, so before you try to match bv., you’ll want to flatten the inner text nodes a bit.

Here’s one straightforward approach:

function cleanAndMergeSpans(container) {
  const spans = container.querySelectorAll('span');
  spans.forEach(span => {
    // Move the text content up to the parent node
    const textNode = document.createTextNode(span.textContent);
    span.parentNode.insertBefore(textNode, span);
    span.remove();
  });
}

You can call this function on the main container that holds your content, e.g.

cleanAndMergeSpans(document.body);

That’ll strip out all span elements (and their attributes) while keeping the text in place so "bv." ends up as one continuous string again.

If you’ve got nested spans or extra markup like <div>s, you can run the same logic recursively or simply do something like:

document.body.innerHTML = document.body.textContent;

but be careful with that one, since it’ll remove all HTML formatting.

So, in short: remove the wrapping spans, keep the text nodes, then your highlight function should work as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.