Categories
JavaScript Answers

How to replace a text node with HTML text in JavaScript?

Spread the love

Sometimes, we want to replace a text node with HTML text in JavaScript.

In this article, we’ll look at how to replace a text node with HTML text in JavaScript.

How to replace a text node with HTML text in JavaScript?

To replace a text node with HTML text in JavaScript, we can set the innerHTML property of the element to the HTML we want.

For instance, we write:

<span>
  https://example.com
</span>

to add a span.

Then we replace the HTML inside the span by writing:

const span = document.querySelector('span')
span.innerHTML = `<a href='${span.textContent}'>${span.textContent}</a>`

We get the span with querySelector.

Then we set the innerHTML property of the span to the HTML we want to replace it with.

As a result, we see the link rendered in the span.

Conclusion

To replace a text node with HTML text in JavaScript, we can set the innerHTML property of the element to the HTML we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.