Hi all.

I basically need to know how to get a link's href value using the getelementbytagname code and storing that value in a variable so it can be used later in the same function.

Thanks,

Max

Recommended Answers

All 3 Replies

Member Avatar for langsor

Hi,

If you need to handle all links on the page this way, then use something like this ...

window.onload = function () { // wait until the page is loaded
  var links = document.getElementsByTagName('a');
  for ( var i = 0; i < links.length; i ++ ) {
    link.item(i).onlick = function () {
      // store the href of link on click here
      alert( this.href ); // or alert( this.getAttribute('href'); // more proper
    };
  }
};

If you just need one links href when it is clicked then something like this ...

window.onload = function () { // wait until the page is loaded
  var link = document.getElementById('one_link');
  link.item(i).onlick = function () {
    // store the href of link on click here
    alert( this.href ); // or alert( this.getAttribute('href'); // more proper
  };
};
</script>
</head>
<body>
<a id="one_link" href="some_page.html">One Link</a>

... more stuff ...

There are other approaches as well, but this is a pretty standard way to do it.

Cheers

Member Avatar for langsor

Right, using it later in the same function ... easy enough

var active_href = this; // from above code.

Let me know if this is not what you meant or have any questions about this.

That worked thanks. (I used the last one)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.