Get href string javascript

How to Get href in JavaScript

href” stands for a hypertext link. While developing a website, the URL of the page to which the link points is specified using the HTML anchor “ ” tag. In certain scenarios, the developers need to determine the value of the href, which is the page’s URL. To do so, JavaScript has some built-in methods that can assist you.

This manual will discuss the ways to get the href value of the JavaScript anchor tag.

How to Get href in JavaScript?

To determine the href value in JavaScript, use the following JavaScript predefined methods:

Let’s examine these approaches individually!

Method 1: Get href Using getAttribute() Method

The “getAttribute()” method of the Element interface gives the value of a particular attribute of the defined element. The return value is null or the empty string if the desired attribute is missing.

Follow the given syntax for getting the href using getAttribute() method:

Here, “attributeName” is the name of the attribute whose value we want to get.

Example: Get href Using querySelector() Method With getAttribute() Method

We will first, create an anchor tag, button and a label for printing URL that will get the href value using JavaScript “getAttribute()” method:

Next, define the “getUrl()” function in JavaScript file, where we will first, get the anchor tag using “querySelector()” method and then call the getAttribute() method by passing href as an argument. It will find out the first anchor tag and retrieve its URL and store it in the “href” variable. Finally, prints the value as the text of the added label:

function getUrl ( ) {
var href = document.querySelector ( ‘a’ ) .getAttribute ( ‘href’ ) ;
var url = document.getElementById ( ‘getUrl’ ) ;
url.textContent = ` The URL is $ ` ;
}

The output displays the value of href on a button click:

Let’s move to the next method for getting href in JavaScript.

Method 2: Get href Using href Attribute

The other method for getting href value is the “href” attribute. The href is the property of the “HTMLAnchorElement” that updates the href and gives a string with the complete URL.

Use the following syntax for getting the href value with the help of the “href” attribute:

Example: Get href Using getElementById() Method With href Attribute

We will consider the same link in the anchor tag used in the previous example. Then, in the “getUrl()” function, first access the anchor tag by passing the “link” id of the anchor tag in the “getElementbyId()” method and call the “href” attribute with it. Next, again get the added label using the same procedure and set the value of the fetched href as its content:

Читайте также:  Векторное произведение векторов питон

function getUrl ( ) {
const value1 = document.getElementById ( «link» ) .href;
const url = document.getElementById ( ‘getUrl’ ) ;
url.textContent = ` The URL is $ ` ;
}

We have provided the simplest solution for getting the href value in JavaScript.

Conclusion

To get the href in JavaScript, you can utilize the JavaScript predefined methods, such as getAttribute() method and href attribute. The only thing that separates the getAttribute() method from the href attribute is that it returns the value of the anchor element while the href gives the whole path to which the anchor element points. In this manual, we have discussed the ways to get the href value of the JavaScript anchor tag.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Get href in JavaScript

Get href in JavaScript

  1. Get Href or Location in JavaScript
  2. Use getAttribute() to Get Href in JavaScript
  3. Use href Attribute to Get Href in JavaScript

The article will teach how to get the href/location in JavaScript. The JavaScript widget offers two choices; the first uses the location attribute, and the second uses the open method.

Get Href or Location in JavaScript

The location interface represents the location (URL) of the object to which it is linked. The Document and Windows interfaces have an associated location that can be accessed via document.location or window.location .

The biggest difference between them is their browser compatibility. The window.location is read/written by all supported browsers.

The document.location is read-only in IE but read/write in Gecko-based browsers like Firefox.

To communicate with the browser, JavaScript provides the main window object. Represents the browser window.

All global variables and functions become members of the widget. The window position object is used to get the URL of the current page and also change the redirect URL.

Use getAttribute() to Get Href in JavaScript

The Element interface’s getAttribute() method returns the value of a specified attribute for the element. If the specified attribute does not exist, the return value is null or » » (the empty string).

const attributeOutput = element.getAttribute(attributeName); 

The attributeName is the attribute’s name whose value you want to retrieve. It returns the string containing the value of attributeName .

Further information on the getAttribute function can be found in the documentation for the getAttribute .

a id="google" href="https://www.google.com">a> a id="local" href="aboutUs">a> 
const value1 = document.getElementById("google").getAttribute("href"); const value2 = document.getElementById("local").getAttribute("href"); console.log(value1); console.log(value2); 

In the above code, we use the element’s getAttribute method to fetch the value of a select attribute associated with the requested element. Once you run the above code in any browser, it’ll print something like this.

"https://www.google.com" "aboutUs" 

Use href Attribute to Get Href in JavaScript

The HTMLAnchorElement.href property is a stringifier that returns a USVString containing the full URL and allows the href to be updated.

Читайте также:  Php если нет то создать папку

The sole difference between the getAttribute() and href attribute is that prior returns the value of the anchor element. In contrast, the latter returns the full path where the anchor element points.

// Getting href  string = anchorElement.href; // Setting href  anchorElement.href = string; 
a id="google" href="https://www.google.com">a> a id="local" href="aboutUs">a> 
const value1 = document.getElementById("google").href; const value2 = document.getElementById("local").href; console.log(value1); console.log(value2); 

In the above code, we use the href attribute of the anchor element, which will give the full path where the anchor element points. Once you run the above code in any browser, it’ll print something like this.

"https://www.google.com/" "https://fiddle.jshell.net/_display/aboutUs" 

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

Related Article — JavaScript Href

Источник

How to Get Current URL in JavaScript [with Useful Examples]

To get the current URL of the page you are visiting using JavaScript, access the window.location.href property:

Alternatively, you can access the current URL via document.URL property. However, it has some shortcomings that I’ll explain in a bit.

Let’s take a closer look at the window.location object. It has useful properties other than the href that returns the URL.

window.location

As you learned in the introduction already, window.location object is useful because you can retrieve the current page URL with it.

By the way, it’s possible to change the window.location object properties, such as the URL.

The window.location object has other useful properties too. Before accessing the properties, let’s take a quick look at the URL parts.

URL Structure

Let’s quickly go through the basic URL structure to distinguish the parts in it.

  • Protocol. The protocol is the “first part” of a URL. It specifies which protocol to use to access the resource on the internet. Protocols include HTTP, HTTPS, or FTP.
  • Subdomain. A domain can be split into logical sections, called subdomains. The most common example is www, which means the domain is (automatically) part of the world wide web subdomain. Better examples of subdomains are store, blog, or app. For example, app.example.com, or blog.example.com.
  • Domain Name. The domain name is the actual address of your website. It is the host that owns the resources of your site. For instance, example.com is a domain name.
  • Port. The port is an optional part of a URL because it’s set automatically. It is a number that determines the “gate” via which you want to retrieve the resources.
  • File Path. The file path is like a file path on your computer. On a website, the web pages are files on a server. To access a particular web page, you need to specify the path to it on a server. For example, https://www.example.com/calculator.html.
  • Query Parameters. Query parameters can be inserted into a URL to perform an action like a search on the server.
  • Fragment. Fragment, hash, or anchor is used to specify a part of a page to be accessed. For example, example.com/blog/what-is-url#chapter1
Читайте также:  Jdbc connection string in java mysql

Now you understand what makes up a URL.

In JavaScript, you can use the window.location object to access these URL parts. Let’s take a look at the window.location properties a bit closer.

If you are unfamiliar with URLs, make sure to read a comprehensive guide, What Is a URL?

Access URL Parts with window.location Properties

The window.location object has the following properties in JavaScript:

  • href. The entire URL of your current page.
  • protocol. The protocol that the URL uses.
  • host. The hostname and the port of a URL.
  • hostname. The hostname of a URL.
  • port. The port of the URL.
  • pathname. The file path in the URL.
  • search. The query parameters of the URL.
  • hash. The fragment or anchor of the URL.
  • origin. A Combination of the protocol and host of the URL.

Here are examples of accessing these properties when the URL is https://www.codingem.com/best-pixel-art-software/#photoshop.

To make it easier to see, here is a zoomed-in image of accessing the URL properties.

Besides getting the current URL of a page, you can access parts of the URL easily. Instead of using regex or other heuristics to split the URL string, you can use the window.location properties to your advantage. This is the main way to operate with URLs using JavaScript.

Before you go, let’s talk about a commonly seen alternative, document.URL.

Get the Current URL with document.URL

Another popular way to get the current URL of a page is by accessing the URL property of the document.

Unlike window.location.href, the document.URL gives you a read-only string that represents the current page’s URL. So if you don’t want to make changes to the URL string, then it might make more sense to use document.URL over window.location.href.

But the problem with document.URL approach is it has some bugs in Firefox.

For example, in Firefox 12, the document.URL doesn’t change when adding an anchor to the end of a URL.

So if you want to be 100% sure to get the URL and all of its parts, use the window.location.href.

Wrap Up

Today you learned how to get the URL of a current page using JavaScript.

To put it short, use the window.location.href property to access the URL of the page. Keep in mind you can directly modify this property as well.

To get a read-only URL string, you might consider using the document.URL. But remember it has some bugs with Firefox.

Источник

Оцените статью