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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With