I have a button in HTML and I want to forward to another page when clicked
(function() {
'use strict';
window.addEventListener('DOMContentLoaded', init, false);
function init() {
let url = document.getElementsByClassName("Button__LandingPage");
url.addEventListener("click", forwardURL, false);
function forwardURL() {
location.replace("https://www.w3schools.com");
}
};
})();
<button class="Button Button__LandingPage" name="landingPageButton">Home</button>
What do I wrong here? Thanks for any help.
getElementsByClassName
returns a collection not a single result. It would be better to use an id with getElementById
instead. But, in your case, you can get the first element of the collection with getElementsByClassName[0]
. Here's a full example:
(function() {
'use strict';
window.addEventListener('DOMContentLoaded', init, false);
function init() {
let url = document.getElementsByClassName("Button__LandingPage")[0];
url.addEventListener("click", forwardURL, false);
function forwardURL() {
//location.replace("https://www.w3schools.com");
console.log("Forward");
}
};
})();
<button class="Button Button__LandingPage" name="landingPageButton">Home</button>