Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When creating a hyperlink using javascript, the page displays the href address instead of textNode

I am trying to create a hyperlink using Javascript and then include it in a paragraph in my webpage, which i am appending to my div with an id of ‘content’. Any way I try, I can only get the actual address to show up in the page (and the link does not work at all). Here’s what I’ve tried:

const content = document.querySelector('#content');
const paragraph = document.createElement("p");
const link = document.createElement("a");
const text = document.createTextNode("Click here");

link.title = "My Link Title";
link.href = "https://www.google.com";
link.appendChild(text);  
  
paragraph.innerHTML = `This is my paragraph. ${link} to go to google.`;

content.appendChild(paragraph);
<div id="content"></div>

With this code, the paragraph shows up in my website as "This is my paragraph. https://www.google.com to go to google." (but there is no clickable link)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.innerHTML only accepts strings, not elements – and when you do ${link}, you’re coercing the <a> to a string and interpolating that string.

When an anchor is cast to string, the href is the result. (If the anchor has text content, it’s ignored.)

const a = document.createElement('a');
a.textContent = 'foo';
a.href = 'https://example.com';
console.log(String(a));

Don’t interpolate your anchor into a string – instead, append the anchor as an element.

const content = document.querySelector('#content');
const paragraph = document.createElement("p");
const link = document.createElement("a");
const text = document.createTextNode("Click here");

link.title = "My Link Title";
link.href = "https://www.google.com";
link.appendChild(text);  

paragraph.appendChild(link);
paragraph.insertAdjacentText('afterbegin', 'This is my paragraph. ');
paragraph.insertAdjacentText('beforeend', ' to go to google.');

content.appendChild(paragraph);
<div id="content"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading