3

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.

2
  • 2
    "when i output it to a div" - show how you do it. Commented Jul 14, 2015 at 21:04
  • Where is the show() function. You're assigning the msg variable from the return value of the show() function and then returning that. Commented Jul 14, 2015 at 21:11

3 Answers 3

4

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

Example:

document.querySelector( ".msg" ).innerHTML = "Visit <a href='http://bing.com'>Bing</a>.";
<div class="msg"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.