4

I have multiple whole html code in variable cleanHTML and i need to strip specific tags from text.

let cleanHTML = document.documentElement.outerHTML

this:

<span class="remove-me">please</span>
<span class="remove-me">me too</span>
<span class="remove-me">and me</span>

to this:

please
me too
and me

I´m trying to do it with:

var list = cleanHTML.getElementsByClassName("remove-me");
var i;
for (i = 0; i < list.length; i++) {
  list[i] = list[i].innerHTML;
}

But i´m getting error from React cleanHTML.getElementsByClassName is not a function

Any idea how to do it in a way React likes?

2
  • cleanHTML is just a string? You could theoretically load it with a xmldoc parser, and then get the textContent (you don't want any html in your react jsx) Commented Sep 10, 2018 at 12:40
  • >([^>]*)<? $1 Commented Sep 10, 2018 at 12:50

2 Answers 2

13

Your cleanHtml is a string and not a node. So getElementsByClassName does not apply as it is not a string function

You can use regular expressions to do this. Following code might help.

var stripedHtml = cleanHtml.replace(/<[^>]+>/g, '');

And stripedHtml will have your html content without tags.

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

1 Comment

I know that this will stripe all the tags, but i´m trying to stripe out only tags with a specific class
1

I am guessing from your specification that your cleanHTML is a string, so you would need to convert the string to a node (eg: by creating a div from it), and then parsing the nodes appropriately.

Please note that you really need to request the textContent and not the innerHTML, as you do not want to have any html in your react output

const htmlContent = `<span class="remove-me">please</span>
<span class="remove-me">me too</span>
<span class="remove-me">and me</span>`;

const getNodesToRemoveFromElement = (stringContent) => {
  const el = document.createElement('div');
  el.innerHTML = stringContent;
  return el.getElementsByClassName('remove-me');
};

for (let node of getNodesToRemoveFromElement( htmlContent ) ) {
  console.log( node.textContent );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.