First let assume the prop which holds the paragraph is content.
Before rendering content you need parse it and alter it as a String, to do that add this method to you component
AddLeadingSpan( content ){ // pattern for the openeing P tag const targetEl = /<p>/gi; // substitute for the matching result const subsEl = "<p><span>im a span tag </span>"; // add some text for relevance // simply use the native string API to do the replacement return content.replace( targetEl, subsEl); }
the above method shouldn't be called directly from the render function due to the fact that it returns a string which will be printed as a string.
To solve that problem we need another method (which in this case will act as a middleware ) :
renderAsHTML( content ){ return( {__html:this.AddLeadingSpan( content ) } ) }
Finally let go to the render method:
render(){ return( <div dangerouslySetInnerHTML={this.renderAsHTML( this.props.content )}> </div> ) }
You need to invoke the dangerouslySetInnerHTML to do things the React way, for more info check dangerouslySetInnerHTML, but you need to sanitize content to prevent against cross-site scripting (XSS)
const pTags = document.querySelectorAll('p');for (let i = 0; i < pTags.length - 1; i++) { pTags[i].prepend(document.createElement('span')); }