Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating link in JavaScript, and integrating it into createTextNode()

Tags:

javascript

I'm looking to integrate a link into a created text node, but it comes up as just the text (title), not the link. How do I fix this?

Code in the function:

function createMessage() {
   var a = document.createElement('a');
   var linkText = document.createTextNode("http://www.example.com");
   a.title = "http://www.example.com";
   a.href = "http://www.example.com";
   var message2 = document.createElement("p");
   var message2text = document.createTextNode("Website: " + a + ".");
   message2.appendChild(message2text);
   var olElem = document.getElementById("display");
   var old = document.getElementById("display");
   var display = old.parentNode;
   return display.replaceChild(message2, olElem);
}
like image 920
cfleming93 Avatar asked Dec 24 '22 21:12

cfleming93


1 Answers

Problem here:

var message2text = document.createTextNode("Website: " + a + ".");
// ---------------------------------------------------^^^^^^^

You can't append a DOM element to a string and get a useful result.

It's hard to figure out what you're trying to do in your code, but to create a paragraph containing a link, the simplest way is innerHTML:

var p = document.createElement('p');
p.innerHTML = 'Website: <a href="http://example.com" title="http://example.com">http://example.com</a>.';

...and then append/insert that where desired.

But if you want to do it in bits and pieces, it's:

var a = document.createElement('a');
a.href = "http://example.com";
a.title = "http://example.com";
a.appendChild(document.createTextNode("http://example.com"));
var p = document.createElement('p');
p.appendChild(document.createTextNode("Website: "));
p.appendChild(a);
p.appendChild(document.createTextNode("."));

...and then append/insert that where desired. Note how we had to create three separate text nodes: The text before the link, the text within the link, and the text after the link.

like image 57
T.J. Crowder Avatar answered Dec 27 '22 10:12

T.J. Crowder