Reputation: 1444
I am building a reactjs application. I get html content as string. For example:
state= {elem:`<div>
<p>...</p>
<a href="www.twitter.com"></a>
<h1>Heading</h1>
<div>
<a href="www.facebook.com"></a>
</div>
</div>`.}
I will be setting this in my dom using <div dangerouslySetInnerHTML={this._createMarkup()} />
_createMarkup = () => {
return { __html: this.state.elem};
};
Instead of directly rendering this html snippet in the dom, I need to parse it and make modifications. That is, wherever there is an anchor tag, I need to append http:// if it is not present in the href attribute. There can be multiple anchor tags in the snippet. How can I achieve this?
Upvotes: 1
Views: 2165
Reputation: 28397
You can use DOMParser
, which is widely supported, in order to achieve that.
Here's a little snippet.
const parser = new DOMParser();
const htmlText = `<div>
<p>...</p>
<a href="www.twitter.com">Twitter</a>
<h1>Heading</h1>
<div>
<a href="www.facebook.com">Facebook</a>
</div>
</div>`;
let content = parser.parseFromString(htmlText, "text/html");
const anchors = content.getElementsByTagName('a');
Array.from(anchors).forEach(v => {
const href = v.getAttribute("href");
if (!href.includes('http://')) {
v.href = 'http://' + href;
}
})
console.log(content.body.innerHTML); // Here it is your new string
const App = () => (
<div>
<div dangerouslySetInnerHTML={{ __html: content.body.innerHTML}} />
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
Upvotes: 2