PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

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

 October 15, 2022     dom, html, javascript     No comments   

Issue

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)


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>



Answered By - CertainPerformance
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing