Hướng dẫn set href javascript

An Visit W3Schools

Try it Yourself »

More "Try it Yourself" examples below.

Definition and Usage

The href attribute specifies the URL of the page the link goes to.

If the href attribute is not present, the or href="#" to link to the top of the current page!

Browser Support

Attribute
href Yes Yes Yes Yes Yes

Syntax

Attribute Values

ValueDescription
URL The URL of the link.

Possible values:

  • An absolute URL - points to another web site [like href="//www.example.com/default.htm"]
  • A relative URL - points to a file within a web site [like href="default.htm"]
  • Link to an element with a specified id within the page [like href="#section2"]
  • Other protocols [like //, ftp://, mailto:, file:, etc..]
  • A script [like href="javascript:alert['Hello'];"]

More Examples

Example

How to use an image as a link:



Try it Yourself »

Example

How to link to an email address:

Send email

Try it Yourself »

Example

How to link to a phone number:

+47 333 78 901

Try it Yourself »

Example

How to link to another section on the same page:

Go to Section 2

Try it Yourself »

Example

How to link to a JavaScript:

Execute JavaScript

Try it Yourself »

❮ HTML tag

❮ Anchor Object

Example

Change the destination [URL] of a link:

document.getElementById["myAnchor"].href = "//www.cnn.com/";

Try it Yourself »

Definition and Usage

The href property sets or returns the value of the href attribute of a link.

The href attribute specifies the destination of a link.

Browser Support

Property
href Yes Yes Yes Yes Yes

Syntax

Return the href property:

Set the href property:

Property Values

ValueDescription
URL Specifies the URL of the link.

Possible values:

  • An absolute URL - points to another web site [like href="//www.example.com/default.htm"]
  • A relative URL - points to a file within a web site [like href="default.htm"]
  • An anchor URL - points to an anchor within a page [like href="#top"]

Technical Details

Return Value:
A String, representing the URL of the link. Returns the entire URL, including the protocol [like //]

More Examples

Example

Get the URL of a link:

var x = document.getElementById["myAnchor"].href;

Try it Yourself »


Example

Another example of how to get the URL of a link [a relative URL]:

var x = document.getElementById["myAnchor"].href;

Try it Yourself »

Related Pages

HTML reference: HTML href attribute

❮ Anchor Object


Chủ Đề