Reputation: 315
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.
Upvotes: 3
Views: 13174
Reputation: 7182
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
Upvotes: 2
Reputation: 131
This is a basic example on how to insert html using plain javascript:
document.getElementById('your-div').innerHTML = msg
Here is a fiddle of your case: demo
Upvotes: 1
Reputation: 268334
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>
Upvotes: 4