Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use DOM methods to create and insert an anchor

Status
Not open for further replies.

Pav1977

IS-IT--Management
Jul 5, 2006
59
GB
I believe I need to use DOM methods to create and insert an anchor object into a document. And I'm not sure how to do it.

I'm trying to write a script that will pass the url of the current page to the 'stumbleupon' site to be bookmarked.
My script is:

<script type="text/javascript">
function getHost()
{
var url = window.location.href;
var bookmarkpart1='<a href="
document.write(bookmarkpart1+url+'"> <img border=0 src=""**LINK TO stumbleit.gif**"" alt="StumbleUpon Toolbar"> Stumble It!</a>')
}
</script>

<script type="text/javascript">
getHost();
</script>

Unfortunately it's for some reason not writing the value of the variables (bookmarkpart1 and url but writes them as string on the page.
What am I doing wrong???

if I call it with for example

<body onload="getHost()">
</body>

it works fine but that's not how I want it.

Any help would be much appreciated.

Pav
 
If you call "document.write" after the page has loaded, it will replace the contents of the page.

You want something like:

Code:
var baseUrl = '[URL unfurl="true"]http://www.stumbleupon.com/submit?url=';[/URL]

var anchor = document.createElement('a');
anchor.href = baseUrl + window.location.href;

var img = document.createElement('img');
img.border = '0';
img.src = 'stumbleit.gif';
img.alt = 'StumbleUpon Toolbar';
anchor.appendChild(img);

var linkText = document.createTextNode('Stumble It!');
anchor.appendChild(linkText);

document.getElementsByTagName('body')[0].appendChild(anchor);

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top