Lawless Leopard
Lawless Leopard

Reputation: 69

How to add an anchor tag in the middle of a <p> element when using document.createElement("p")

I'm using document.createElement("p") to dynamically create elements. I need to create an element <p></p> with an anchor tag in the middle of it so it creates a link word.

I want to be able to inject the following html using Javascript using document.createElement("p"):

<p> This is a <a href="google.com">link</a> to google</p>

The word link should be an anchor tag surrounded by text from the <p> tag.

Upvotes: 0

Views: 1160

Answers (1)

Lucky
Lucky

Reputation: 2082

You can use innerHTML

let p = document.createElement('p');
p.innerHTML = "This is a <a href=\"http://www.google.com\">link</a> to google";

// append it
document.body.appendChild(p);

Upvotes: 1

Related Questions