Home > Web Front-end > JS Tutorial > How Can I Change Hyperlink Targets Using jQuery?

How Can I Change Hyperlink Targets Using jQuery?

Linda Hamilton
Release: 2024-12-16 09:34:11
Original
175 people have browsed it

How Can I Change Hyperlink Targets Using jQuery?

Modifying Hyperlink Target with jQuery

Problem: How to alter the 'href' attribute of a hyperlink using jQuery?

Solution:

To modify hyperlink targets, utilize the following syntax:

$("a").attr("href", "new_target")
Copy after login

where "a" represents the selector for the hyperlinks, and "new_target" is the desired destination.

Example:

To redirect all hyperlinks to Google, use:

$("a").attr("href", "http://www.google.com/")
Copy after login

Refinement:

To select specific hyperlinks, use a refined selector:

$("a[href]")
Copy after login

This targets hyperlinks with existing 'href' attributes.

Advanced Modification:

For more intricate modifications, such as matching specific hrefs or updating only part of the href, use a combination of selectors and jQuery functions:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Copy after login

This finds hyperlinks that match the specific href and updates their targets to 'http://www.live.com/'.

$("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });
Copy after login

This selects hyperlinks that begin with 'http://stackoverflow.com', then uses a regular expression to replace the prefix with 'http://stackoverflow.com'.

The above is the detailed content of How Can I Change Hyperlink Targets Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template