new to this javascript thing. This is driving me crazy!
How do I add a URL in a string variable?
This is what I have:
function getRiskMessage(){
var msg = " visit our advice website at <a href=\'http://www.example.com\'>this site</a>";
if(totalRiskScore > 25){
//this message (High Risk)
msg2 = show();
}//close if
return msg;
}
but when i output it to a div instead of a link 'this link' - I get the a tag and url as string like above.
What am I doing wrong, need to understand this.
tl;dr You're using createTextNode, which creates a plain-text node. Don't do that :) Use the innerHTML property instead. See below for more details.
You don't need to escape quotes unless they resemble the start and end quotes:
var foo = "Visit <a href='http://bing.com'>Bing</a>.";
In the above, the string begins and ends with double-quotes, so single-quotes can be used without any problems.
var foo = "Visit <a href=\"http://bing.com\">Bing</a>.";
In the above, we use double-quotes around the string, and around the [href] attribute. As a result, the inner-quotes (around the attribute) must be escaped so they don't confuse the parser.
Lastly, when you output, make sure to output as HTML:
div.textContent = foo; // Represents foo as plain text
div.innerHTML = foo; // Interprets foo as HTML
div.appendChild( document.createTextNode( foo ) ); // Similar to textContent
div.appendChild( document.createElement( "span" ) ).innerHTML = foo; // HTML
document.querySelector( ".msg" ).innerHTML = "Visit <a href='http://bing.com'>Bing</a>.";
<div class="msg"></div>
Thy this:
var msg = document.createElement('span');
msg.innerHTML = " visit our advice website at <a href=\'http://www.example.com\'>this site</a>"
container.appendChild(msg);
Working demo: FIDDLE
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