How to change the href attribute for a hyperlink in jQuery
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.
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 theattr()function to set a new value to thehrefattribute.