简体   繁体   中英

how can I create a link with element.appendChild

I'm using the following Javascript code in order to extract an information from the current webpage through an extension. I posted only partial and relevant code because all is very long, I have no issue with this code, I get the company name in output on the current page with no issue. Now, I need that the same text comes to output as a link "", so that I can click on it and open the webpage I link to this text. I suppose I should change element.appendChild(organ); but I have no idea how to make it a link. Would you mind to suggest me something? Please ask for more details if you need. Thank you very much in advance.

 var enrollmentField = $('input[class="inputField-textBox"]'); var getOrg = $(enrollmentField[0]).val(); var newOrg = "<span class='greyc'>" + getOrg + "</span>"; var organ = document.createTextNode("Organization: "); element.appendChild(organ); document.getElementById("myList").appendChild(organ); $(newOrg).appendTo('#myList'); 

 const orgInput = document.getElementById('organisation'), a = document.getElementById('a'); function setA(){ a.innerText = orgInput.value; a.href = orgInput.value; } 
 <input type="text" id="organisation"> <input type="button" onclick="setA()" value="create"/> <a id="a"></a> 

You can use something like this:

let a = document.createElement('a');
let anchorText = document.createTextNode("Organization name");
a.appendChild(anchorText);
a.title = "Open organization webpage";
a.href = "http://example.com";
document.body.appendChild(a);

I could solve in this way and works:

 orglink = "<a href='" + webSite + "' target='_blank'>" + newOrg + "</a>"; 

Thank you very much for your help guys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM