How to Create a Link Using JavaScript

How do I create a link using javascript?

<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>

Using Javascript to create a link element and then adding it to head section

This is working :

    var fontLoader = function (param) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';

//link.href = 'http://fonts.googleapis.com/css?family=Oswald&effect=neon';
document.head.appendChild(link);

link.href = 'http://fonts.googleapis.com/css?family=' + param.family + '&effect=' + param.effect;


};

fontLoader({
family: 'Oswald',
effect: 'neon'
});
.normal , .oswald {
padding : 3px;
margin : 3px;
color : #333;
border : solid 1px #CCC;
font-size : 2em;

}
.oswald {

font-family:'Oswald';

}
<div class='normal'>Normal Style</div>
<div class='oswald'>Oswald Style</div>

Using JavaScript's Document.write() to create a HTML link

This might work instead of document.write().

<html>
<head></head>
<body>
<div id="Place to insert"></div>
<script>
var link = document.createElement('a');
link.textContent = 'Link Title';
link.href = Your URL;
document.getElementById('Place to insert').appendChild(link);
</script>
</body>
</html>

Create a link and click it on a single button click

It seems you really just want to change the location of the page, and not actually append a link at all:

location.href = 'your link you got back'

If you actually want a physical link to be added on the page:

var link=document.createElement("a");
link.id = 'someLink'; //give it an ID!
link.href="http://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using- javascript";

//Add the link somewhere, an appendChild statement will do.
//Then run this
document.getElementById('someLink').click();

How to add a tag and href using javascript

This is the way to create anchor use createElement() and setAttribute() and then appendChild() to append it to your div

var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.textContent= "link text";
mydiv.appendChild(aTag);

Create a url link on a text inside a cell using javascript

IDs are meant to be unique. That's why the first time you do td1.setAttribute("id","sn"); that becomes the one and only cell with that ID.

What you need to do is use references and not IDs, like this:

var idCell = document.createElement('td');
idCell.innerHtml = '<a href="javascript:void(0)" onclick="editStation(' + stationId + ')">' + stationId + '</a>';
tr.appendChild(idCell)

The code below works as you'd expect and it is more memory efficient. I changed your HTML a little bit (moved repetitive styles one level up and removed that table row that you don't actually need):

<body onload="viewStations()">
<div class="row">
<div class="col-sm col-md col-lg col-xl">
<table id="stationtable" class="table table-borderless table-hover" style="border-style:solid; border-width:0px;width:100%; height:auto; margin-radius:5px;">
<thead>
<tr style="color:brown; font-weight:bold; font-size:18px; text-align:center;">
<th style="width:5%">SN</th>
<th style="width:35%">STATION NAME</th>
<th style="width:40%">ADDRESS</th>
<th style="width:20%">ZONE</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>

<button id="view" onclick="viewStations()">LOAD STATIONS </button>
</div>
</div>
</body>

And here's the Javascript (I changed your functions a little):

// This is the only variable you need.
var db = openDatabase('pcrdb', '3.6.19', 'Police Criminal Records Database', 500*1024*1024);//500MB

function editStation(stationId){
alert("This link is not working yet. The station id is: " + stationId);
}

function viewStations (){
document.getElementById("viewbutton").disabled = true;

db.transaction(function (tx) {
tx.executeSql('SELECT * FROM STATIONS', [], function (tx, results) {

// There's no need to save the information in global
// variables, just pass on the object you need.
for (var i=0; i<results.rows.length; i++) {
createCells(results.rows.item(i));
};
}, null);
});
}

function createCells(row) {
var tbody = document.getElementById("tbody");

// You need to create new lines
var tr = document.createElement('tr');
var stationId = row['stationid'];

// In this case your first cell needs a different treatment
var idCell = document.createElement('td');
idCell.innerHtml = '<a href="javascript:void(0)" onclick="editStation(' + stationId + ')">' + stationId + '</a>';
tr.appendChild(idCell);

// When handling several near identical lines it is better
// to just use arrays. In this one, your columns are simply
// properties of an object.
['stationName', 'address', 'zone'].forEach(
function (column) {
var td = document.createElement('td');
td.innerText = row[column];
tr.appendChild(td);
}
)

// finally append the new line
tbody.appendChild(tr);
}

That should do it.

Javascript setting html created element link

links are anchor tags <a> so you would use document.createElement("a")

If you want the link to be h3 styling just append the link to that element, or use css

var link = document.creaetElement("a");
datasheet.appendChild(link);

var link = document.createElement("A");link.href = "https://stackoverflow.com";link.textContent = "Link to stackoverflow";document.body.appendChild(link);
var linkClone = link.cloneNode(true);var datasheet = document.createElement("h3");
datasheet.appendChild(linkClone);document.body.appendChild(datasheet);

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

window.history.length (Integer)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

Lets say a user visits your page, clicks on some links and goes back:


www.mysite.com/index.html <-- first page and now current page <----+
www.mysite.com/about.html |
www.mysite.com/about.html#privacy |
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

window.goBack = function (e){
var defaultLocation = "http://www.mysite.com";
var oldHash = window.location.hash;

history.back(); // Try to go back

var newHash = window.location.hash;

/* If the previous page hasn't been loaded in a given time (in this case
* 1000ms) the user is redirected to the default location given above.
* This enables you to redirect the user to another page.
*
* However, you should check whether there was a referrer to the current
* site. This is a good indicator for a previous entry in the history
* session.
*
* Also you should check whether the old location differs only in the hash,
* e.g. /index.html#top --> /index.html# shouldn't redirect to the default
* location.
*/

if(
newHash === oldHash &&
(typeof(document.referrer) !== "string" || document.referrer === "")
){
window.setTimeout(function(){
// redirect to default location
window.location.href = defaultLocation;
},1000); // set timeout in ms
}
if(e){
if(e.preventDefault)
e.preventDefault();
if(e.preventPropagation)
e.preventPropagation();
}
return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

See also:

  • W3C: HTML5: 5.4.2 The History interface


Related Topics



Leave a reply



Submit