Trusted answers to developer questions

How to change the href attribute for a hyperlink in jQuery

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

The attr() method in jQuery can be used to set a new attribute value of an element.

Syntax

$(selector).attr(attribute, newValue)

Parameter

  • attribute: This is the name of the attribute whose value has to be changed.
  • newValue: This is the value to be set.

Implementation of attr()

Explanation

In HTML:

  • We define an anchor element and a button element.

In JavaScript:

  • Line 3: We define a function that will be executed with the click of the button.
  • Line 4: We use the CSS selector, $("a"), to select the anchor element. We use the attr() function to set a new value to the href attribute.

RELATED TAGS

jquery
Did you find this helpful?