Selecting an element can be done in five ways:
- document.querySelector() Method: It returns the first element that matches the query.
- document.querySelectorAll() Method: It returns all the elements that matches the query.
- document.getElementById() Method: It returns the one element that matches the id.
- document.getElementsByClassName() Method: It returns all the elements that matches the class.
- document.getElementsByTagName() Method: It returns a list of the elements that matches the tag name.
The following methods are used to manipulate the attributes:
- getAttribute() method: It returns the current value of an attribute on the element and returns null if the specified attribute does not exist on the element.
- setAttribute() method: It updates the value of an already existing attribute on the specified element else a new attribute is added with the specified name and value.
- removeAttribute() method: It is used to remove an attribute of the specified element.
Explanation: The link opens https://www.google.com before the button is clicked. when the button is clicked then the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org, Since there is only one <a> tag in the HTML document and we aim to change its attribute value, we use querySelector() and the attribute is updated using setAttribute() method.
Explanation: The link opens https://www.google.com before the button is clicked. When the button is clicked the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org. In this approach, the getElementById() method is used to select the element whose destination URL is to be changed.