views:

78

answers:

5

well what is needed is something like
var link = " http://www.google.com";

< a href= 'link' />

or something like it . so i need to use a var as a href ? anyway to do such thing ?

forgot to mention iam using it under mozilla jetpack - html : "" tag

it worked with "< a href= ' " + link + " ' />

anyone has a better way ?

A: 

Using jQuery this would be

var link = "http://www.google.com";
$("a[href='link']").attr("href", link);

Though this would not degrade gracefully should javascript be turned off and you'd probably want to use something else rather than selecting by the href anyways.

Austin Fitzpatrick
Jetpacks _are_ JavaScript. It's not possible to run them with JavaScript turned off.
Eli Grey
A: 

If you are actually writing both of those lines of code, it would be much easier to use write

<a href="http://www.google.com"&gt;Google&lt;/a&gt;

Otherwise, you will need to use JavaScript to set the href property of your link, which will require getting a reference to it (which means you should set its id property).

So you could write something like:

<a id="myLink">Google</a>

and in your JavaScript have:

document.getElementById("myLink").href=link

but first, please think about whether this is really necessary (or provide some more details in your question).

danben
A: 
var link = "http://www.google.com/";
var linktext = "Google";

document.write("<a href=\"" + link + "\">" + linktext + "</a>";
Joel Etherton
+1  A: 

You should set the href value on the server, it is bad design to use scripting for this.

However, to answer the question, it can be done by using script to set the href property of the A element once it is in the DOM, e.g.:

<a href="<a useful URI if javascript not available>" id="a0">foo</a>

<script type="text/javascript">
  var a = document.getElementById('a0');
  if (a) {
    a.href = "http://www.google.com";
  }
</script>

Of course there are a thousand other ways, all with their pitfalls. So set the value on the server and avoid them all.

-- 
Rob
RobG
A: 

You're using Jetpack, so you can do <a href={link}/>.toXMLString().

If all you want to do is create an <a/> element, use the following.

var anchor = document.createElement("a");
anchor.href = link;
Eli Grey