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

Time:09-02

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)

CodePudding user response:

.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>

  • Related