Href in javascript with target

: The Anchor element

The HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.

Try it

Attributes

This element’s attributes include the global attributes.

Causes the browser to treat the linked URL as a download. Can be used with or without a filename value:

  • Without a value, the browser will suggest a filename/extension, generated from various sources:
    • The Content-Disposition HTTP header
    • The final segment in the URL path
    • The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)
    • download only works for same-origin URLs, or the blob: and data: schemes.
    • How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself.
    • If the Content-Disposition header has different information from the download attribute, resulting behavior may differ:
      • If the header specifies a filename , it takes priority over a filename specified in the download attribute.
      • If the header specifies a disposition of inline , Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.

      The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers:

      • Sections of a page with document fragments
      • Specific text portions with text fragments
      • Pieces of media files with media fragments
      • Telephone numbers with tel: URLs
      • Email addresses with mailto: URLs
      • While web browsers may not support other URL schemes, websites can with registerProtocolHandler()

      Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as the global lang attribute.

      A space-separated list of URLs. When the link is followed, the browser will send POST requests with the body PING to the URLs. Typically for tracking.

      How much of the referrer to send when following the link.

      • no-referrer : The Referer header will not be sent.
      • no-referrer-when-downgrade : The Referer header will not be sent to origins without TLS (HTTPS).
      • origin : The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
      • origin-when-cross-origin : The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
      • same-origin : A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
      • strict-origin : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don’t send it to a less secure destination (HTTPS→HTTP).
      • strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
      • unsafe-url : The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.

      The relationship of the linked URL as space-separated link types.

      Where to display the linked URL, as the name for a browsing context (a tab, window, or ). The following keywords have special meanings for where to load the URL:

      • _self : the current browsing context. (Default)
      • _blank : usually a new tab, but users can configure browsers to open a new window instead.
      • _parent : the parent browsing context of the current one. If no parent, behaves as _self .
      • _top : the topmost browsing context (the «highest» context that’s an ancestor of the current one). If no ancestors, behaves as _self .

      Note: Setting target=»_blank» on elements implicitly provides the same rel behavior as setting rel=»noopener» which does not set window.opener .

      Hints at the linked URL’s format with a MIME type. No built-in functionality.

      Deprecated attributes

      Hinted at the character encoding of the linked URL.

      Note: This attribute is deprecated and should not be used by authors. Use the HTTP Content-Type header on the linked URL.

      Used with the shape attribute. A comma-separated list of coordinates.

      Was required to define a possible target location in a page. In HTML 4.01, id and name could both be used on , as long as they had identical values.

      Note: Use the global attribute id instead.

      Specified a reverse link; the opposite of the rel attribute. Deprecated for being very confusing.

      The shape of the hyperlink’s region in an image map.

      Источник

      Learn how to get the href attribute of any, or specific, clicked links in JavaScript.

      When the user clicks on a link in your HTML document, you want to retrieve the target URL, meaning the value of the href attribute, with JavaScript.

      What is the best way to accomplish this?

      To get the value of the href attribute of a clicked link, create an event listener using AddEventListener() and retrieve the value of the href attribute using Element.target() .

      This tutorial will show you exactly how to do this in two steps.

      First, you will learn how to create an event listener for all links or for specific links. Second, you will learn how to retrieve the value of the href attribute of a link when the user clicks it.

      Creating an Event Listener

      The EventTarget.AddEventListener() method of the EventTarget() Web API in JavaScript lets you create event listeners for when the user clicks on a DOM element in your HTML document.

      This method lets you declare a function that gets called every time the event is fired. From the event, you can read the properties of the DOM element that it was attached to, allowing you to parse the value of the href attribute and store it in a variable.

      The syntax for the AddEventListener() method is as follows:

      // Event listener syntax EventTarget.AddEventListener(type, listener);

      Both the type and the listener arguments are mandatory.

      Type is a string that specifies the event type that you want the event listener to listen for.

      Listener can be an object within the scope of the EventListener Web API, or a function that gets called every time the event is fired.

      In this case, we need to create an event listener for clicks on link elements, meaning elements.

      One of the best ways to do this is to use the Document.querySelectorAll() method. This method lets you create a loop that targets all instances of specific DOM elements using CSS selectors.

      So you can do a simple selection for all links on your HTML page—or a narrowed-down selection of links with a specific id, class, or other.

      Here’s how an event listener for all link clicks looks like:

      // Create event listener for all link clicks document.querySelectorAll('a').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >);

      If you need to narrow down your event listener’s scope to clicks on specific links, for example links with a given id or className , all you need to do is modify your CSS selector:

      // Event listener only for document.querySelectorAll('a.nav-item').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >); // Event listener only for document.querySelectorAll('a#nav-item-01').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >);

      Depending on your implementation requirements, a CSS selector can be as simple as targeting elements or as complex as targeting an n-th element within a parent element or a group of elements.

      Mastering CSS selectors can take your query selection skills to the next level. If you’re a frontend developer, this skill will give you an upper hand in your daily work.

      Retrieving the Href Attribute

      Now that you know how to create event listeners that listen to clicks on links, whether all links or specific links, let’s look at how to retrieve the value of the href attribute from them.

      This can be done by passing on the e parameter to the function,short for “event,” that gets called on click.

      Then, you can use the Event.target() Web API to retrieve the className attribute of the DOM object to which the event in your event listener was attached:

      // Create event listener for all link clicks document.querySelectorAll('a').forEach(link =>   link.addEventListener('click', (e) =>  // Retrieve href and store in targetUrl variable let targetUrl = e.target.href; // Output value of targetUrl to console  console.log('A link with target URL ' + targetUrl + 'was clicked');  >); >);

      If you opened up your browser’s console right now, copy/pasted and ran this code, then clicked on a link or two, you’d observe the following results:

      In Conclusion

      I hope you found this tutorial useful.

      I recently had to tackle this challenge myself as I implemented a data layer for analytics purposes on one of my websites. It took me a few tries (and a couple of hours) to get to the best solution, and I believe this is it.

      If you have any questions, or you want to share other ways to achieve this with the rest of this post’s readers, be sure to leave a reply below.

      1 comment

      Greetings.
      Just what I needed after several hours of trying with a multilevel menu. Excellent tutorial. Thank you very much, very grateful.

      Leave a comment Cancel reply

      • How to Wait for an Element to Exist in JavaScript July 13, 2023
      • How to Check If a Function Exists in JavaScript July 13, 2023
      • How to Remove Numbers From a String With RegEx July 13, 2023
      • How to Check If a String Is a Number in JavaScript July 13, 2023
      • How to Insert a Variable Into a String in PHP July 12, 2023

      We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.

      Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.

      These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.

      To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

      Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

      The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

      The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

      The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

      The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

      Источник

      Читайте также:  Css all select tags
Оцените статью