Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

html - make hyperlink from javascript

I want to use a hyperlink string in HTML page which I want to declare source link (URL) in my js file. Please tell me how can I call that URL from my js into html.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a number of different ways to do this. You could use document.createElement() to create a link element, and then inject the element into the DOM. Or you could use the .innerHTML property of an element that you already have on the page to insert the link using text. Or you could modify the "href" attribute of an existing link on the page. All of these are possibilities. Here is one example:

Creating/Inserting DOM Nodes with DOM Methods

var link = document.createElement('a');
link.textContent = 'Link Title';
link.href = 'http://your.domain.tld/some/path';
document.getElementById('where_to_insert').appendChild(link);

Assuming you have something like this in your HTML:

 <span id="where_to_insert"></span>

Creating/Inserting DOM Content with innerHTML

And another example using innerHTML (which you should generally avoid using for security reasons, but which is valid to use in cases where you completely control the HTML being injected):

 var where = document.getElementById('where_to_insert');
 where.innerHTML = '<a href="http://your.domain.tld">Link Title</a>';

Updating the Attributes of a Named DOM Node

Lastly, there is the method that merely updates the href attribute of an existing link:

 document.getElementById('link_to_update').href = 'http://your.domain.tld/path';

... this assumes you have something like the following in your HTML:

 <a id="link_to_update" href="javascript:void(0)">Link Title</a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...