Maurice Greenland
Maurice Greenland

Reputation: 315

Javascript: Add HTML to string - make a link and add it to output

New to javascript, how do I fix this problem I'm having?

I want to add an a tag to a string variable that i'm creating using a function.

The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).

When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.

This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.

How do I do this?

I tried using link() Method, which also didnt work and had similar output.

I'll only include the relevant script below, the rest works fine...

function makeMessage(){

    for(i in msgArr){

        stringMSG += msgArr[i];

        //do not add a comma after last item
        if(i < msgArr.length - 1){
            stringMSG += ', ';
        }


    }


    var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" +  makeLink();

    return highRiskmsg;
}


function makeLink() {
    var contactLink = document.createElement("a");//create <a> tag
    contactLink.setAttribute("id", "linkC");//set id att for <a> tag
    contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
    var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
    contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag

        return contactLink;
    }

Upvotes: 1

Views: 1190

Answers (2)

Ortiga
Ortiga

Reputation: 8814

As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.

function makeMessage(){
    var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";

    var span = document.createElement('span');
    span.appendChild(document.createTextNode(highRiskmsg));
    span.appendChild(makeLink());

    return span;
}

Fiddle

Upvotes: 2

musefan
musefan

Reputation: 48415

It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.

You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>

The quickest way to fix your code would be just to change the return for the makeLink() function as follows:

return contactLink.outerHTML;

Using outerHTML will return the HTML string for the element, rather than the element itself.

Here is a working example

Upvotes: 3

Related Questions