Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert an html link into an array string?

Tags:

javascript

a bit confused here. I have an array that's full of answers to questions and am having trouble getting the link to appear as.. an actual link. I've tried document.write but it's just breaking my page. Any ideas?

this.answer = [
    'answer1' + '<a href="URL">click here</a>',
    'answer 2', 
    'answer 3'
]

I have no idea how to write the <a href="URL">click here</a> bit to get it to not appear as just a string of text instead of HTML. Any ideas? My array is in a Shadow DOM custom HTML5 element, also. I know how to target the shadow DOM, just not sure of the basic format..

Thanks! - Shan

edit: Thanks for the response, mplungjan. Like this?

this.answer = [
    'answer1' + innerHTML('<a href="URL">click here</a>'),
    'answer 2', 
    'answer 3'
]

this makes the entire thing appear blank on my page, however.. Think I'm formatting it wrong

edit 2 okay trying to fix it based on the answers I got.. I tried this:

 var insertThis = document.getElementById('myElement').innerHTML = '<a href="#">Click here</a>';

 this.answer = [
    'answer1' + insertThis,
    'answer 2', 
    'answer 3'
]

but it's still making my array totally blank :( sorry I am pretty new to arrays it is very confusing to me.. Do i need to put the entirety of my first array item in the innerHTML including the 'answer1' bit?

edit it says that I cannot set innerHTML of null.. but when I console log my element right before I get the element by id it logs it fine.. hmm

like image 418
shan Avatar asked Oct 11 '25 23:10

shan


1 Answers

Like the comments to your post, the text isn't being processed as HTML when you're putting it in the DOM of your page.

You need to set the innerHTML of your element to be a value of the array, like this:

    var answer = [
        'answer1' + '<a href="URL">click here</a>',
        'answer 2', 
        'answer 3'
    ];

    document.getElementById("yourelement").innerHTML = answer[0];
like image 60
helllomatt Avatar answered Oct 14 '25 15:10

helllomatt